我正在自学 C++,我意识到这个问题对某些人来说似乎是补救措施。在我制作的游戏中,作为学习过程的一部分,我希望用户能够选择一个困难,当他们选择一个或另一个时,随机数值范围会发生变化。顺便说一下,我使用的编译器是 x-Code。这是代码:
#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 的值。
最佳答案
case
block 不会打开不同的范围,而是同一个 block 的一部分。您的代码(仅考虑范围)看起来有点类似于:
int secretNumber;
{
int secretNumber = rand() % 10 + 1;
...
int secretNumber = rand() % 50 + 1;
...
int secretNumber = rand() % 100 + 1;
}
在同一个作用域中声明了三个同名的不同变量,这在语言中是不允许的。请注意,switch
中的所有三个声明也会隐藏在外部作用域中声明的变量,这可能不是您想要的。
关于c++ - 重新定义一个int错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18342727/