【发布时间】:2016-02-06 15:05:16
【问题描述】:
过去几天我一直被这个问题困扰,这是我最后的选择。任何输入表示赞赏!提前致谢。
要求是创建一个程序,生成三个随机数,并允许用户猜三个数字,对不同的匹配给予奖励。目前,该程序仅识别一个匹配项,如果匹配多个号码则不会显示。
#include <iostream>
#include <ctime> // Needed for actual random number
#include <cstdlib>
using namespace std;
int main()
{
int guess1, guess2, guess3;
int random1, random2, random3;
int exactCount = 0;
int inexactCount = 0;
/// initialize random seed ///
srand(time(NULL));
/// Generate three random numbers ///
random1 = rand() % 9 + 1;
random2 = rand() % 9 + 1;
random3 = rand() % 9 + 1;
/// Accept three guesses ///
cout << "Guess a number between 1 and 9: ";
cin >> guess1;
cout << "Guess another number between 1 and 9: ";
cin >> guess2;
cout << "Guess another number between 1 and 9: ";
cin >> guess3;
/// Test random numbers ///
cout << "Number 1: " << random1 << endl << "Number 2: " << random2 << endl << "Number 3: " << random3 << endl;
system("PAUSE");
/// Count number of exact and inexact matches ///
if (guess1 == random1){
exactCount++;
}
else if (guess1 == random2 || guess1 == random3){
inexactCount;
}
if (guess2 == random2)
{
exactCount++;
}
else if (guess2 == random1 || guess2 == random3){
inexactCount;
}
if (guess3 == random3){
exactCount++;
}
else if(guess3 == random1 || guess3 == random2){
inexactCount++;
}
int matches = exactCount + inexactCount;
/// Check counts and display winnings ///
if (exactCount == 3){
cout << "JACKPOT!!! Three matching in a row! You win $100!!!";
}
else
{
if (matches == 0) cout << "No matches at all, you lose!" << endl;
else if (matches == 3) cout << "Three matching not in order! You win $50!" << endl;
else if (matches == 2) cout << "Two matching numbers! You win $20!" << endl;
else if (matches == 1) cout << "One matching number! You win $10!" << endl;
}
system("pause");
}
【问题讨论】:
-
inexactCount 是什么意思;在 else if ( ... ) 条件之一?你需要增加它吗?
-
换句话说:
inexactCount;什么都不做;做inexactCount++;. -
我猜你没有了解
for循环和arrays?如果你使用这些概念,这段代码可以减半。 -
我刚刚发布并回答了我认为我已经解决了这个问题:)
-
@svasa - 就是这样!我不敢相信我没有增加不准确的计数!如果他们猜对了,但不是按照确切的顺序,那么不准确的计数就会增加。
标签: c++ if-statement random