我的while循环不起作用。该代码可在Codecademy website编译器上正确运行。然后,我用Visual Studio对其进行编译,在命令提示符下运行它并输入一个数字。即使号码正确,程序也会过早停止。
#include <cstdlib>
#include <iostream>
int main() {
int answer = 8;
int guess;
int tries;
std::cout << "I have a number between 1-10.\n";
std::cout << "Please guess it: ";
std::cin >> guess;
while (guess != 8 && tries < 50) {
std::cout << "Wrong guess, try again: ";
std::cin >> guess;
tries++;
}
if (guess == 8) {
std::cout << "You got it!\n";
}
}
答案 0 :(得分:2)
正如@rsjaffe和@Ken White在评论中所说,android.widget
变量已单位化,这意味着该变量指向的内存位置为“垃圾”(留在内存中)。尝试给它一个初始值,就像这样:
tries
它将实例化并初始化int tries = 0;
变量。