我正在尝试使用 while 循环制作一个简单的数字猜测程序,但即使在找到正确的数字后(我将 num 更改为 5 并且它不起作用),它也不会退出 while 循环。你能告诉我问题出在哪里吗?
int guess;
int num;
cout << "Enter the number (0-10): ";
cin >> guess;
while(guess != num){
int num = rand()%10;
cout << "Nope, keep trying." << endl;
cout << "Enter the number (0-10): ";
cin >> guess;
}
cout << "Congrats, you've found the number!" << endl;
Run Code Online (Sandbox Code Playgroud)
int num = rand() % 10;是num循环体内新变量的声明,它隐藏num在程序顶部的定义:while (guess != num)正在使用后者。
解决办法是改写num = rand() % 10;。
在尝试读取它之前,您需要初始化 num为一个值,否则从技术上讲,您的程序的行为是undefined。考虑重做do while循环。
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |