我在教我自己的C++的一方,我意識到這個問題可能似乎補救一些。在我作爲學習過程的一部分的遊戲中,我希望用戶能夠選擇一個難度,當他們選擇一個或另一個時,隨機數值範圍會發生變化。順便說一句,我使用的編譯器是x-Code。這裏是代碼:一個int錯誤的重定義
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int secretNumber;
int main() //integrate difficulty chooser where easy is a number b/w 1 and 10, norm 1 and 50, and hard is 1 and 100
{
srand(static_cast<unsigned int>(time(0))); //seeds random number by time read on system
int guess;
int choice;
char again = 'y';
cout << "\tWelcome to Guess My Number\n\n";
cout << "Please choose a difficulty:\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n";
cin >> choice;
while (again =='y')
{
int tries = 0;
int secretNumber;
do
{
cout << "Enter a guess: ";
cin >> guess;
++tries;
switch (choice)
{
case 1:
cout << "You picked Easy.\n";
int secretNumber = rand() % 10 + 1;
break;
case 2:
cout << "You picked Normal.\n";
int secretNumber = rand() % 50 + 1;
break;
case 3:
cout << "You picked Hard.\n";
int secretNumber = rand() % 100 + 1;
break;
default:
cout << "You have made an illegal choice.\n";
}
if (guess > secretNumber)
{
cout << "\nToo high!";
}
else if (guess < secretNumber)
{
cout << "\nToo low!";
}
else if (guess == secretNumber && tries == 1)
{
cout << "\nThat's unbelievable! You guessed it in exactly 1 guess";
}
else
{
cout << "\nGreat job, you got it in just " << tries << " guesses!\n";
}
}
while(guess != secretNumber);
cout << "Do you want to play again y/n: ";
cin >> again;
}
return 0;
}
2情況發生在情況2和3,我嘗試重新定義secretNumber的值。
我不太清楚是什麼問題是...? –
您是否打算在每次猜測之後更改數字,對或錯?因爲這就是它現在正在做的事情。如果你希望每場比賽有一個數字,而不是每個猜測,'switch(choice)'語句應該在內部循環之外。 – cHao