问题描述
我正在尝试对数字游戏进行简单的猜测,当答案大于数字时,if else 语句不会触发。 例如,如果数字是 20,而我选择 30 以上的数字,比如 41,它就会结束代码。
#include <iostream>
#include <string>
#include <cmath>
#include <unistd.h>
#include <chrono>
#include <thread>
#include <fstream>
#include <random>
#include <time.h>
#include "functions.h"
using namespace std;
void game() {
int number;
int answer;
cout << "Welcome to the guess the number game!" << endl;
cout << "The computer will generate a random number from 1 to 100 and you will try to guess it."<< endl;
cont();
ran(number,100,1);
START:
cout << number;
system("clear");
cout << "Type your answer here: ";
if (!(cin >> answer)) {
cin.clear();
cin.ignore(10000,'\n');
cout << "THAT IS NOT AN OPTION!" << endl;
sleepcp(250);
system("clear");
goto START;
}
int warmer1;
int warmer2;
warmer1 = number + 11;
warmer2 = number - 11;
if (answer > warmer2) {
if (answer == number) {
cout << "You got it!";
} else if (answer < warmer1) {
cout << "You are close."<< endl;
sleepcp(250);
system("clear");
goto START;
}
} else if (answer > number) {
cout << "Less." << endl;
sleepcp(250);
system("clear");
goto START;
} else if (answer < number) {
cout << "More."<< endl;
sleepcp(250);
system("clear");
goto START;
}
}
int main() {
game();
return 0;
}
谁能帮忙解答一下谢谢!!!
解决方法
当 number 等于 20 且 answer 等于 41 时考虑这个 if 语句。
if (answer > warmer2) {
if (answer == number) {
cout << "You got it!";
} else if (answer < warmer1) {
cout << "You are close."<< endl;
sleepcp(250);
system("clear");
goto START;
}
} else if (answer > number) {
在这种情况下,if 语句获得控制权,因为 answer 大于warmer2。但是 answer 不等于 number (第一个内部 if 语句)并且 answer 不小于warmer1。
在这种情况下,什么都没有发生,控制权被传递到程序的末尾。
就是if这个if语句
if (answer > warmer2) {
获取控制然后下面的 if 语句,例如这个
} else if (answer > number) {
将被跳过。
换句话说,你所做的就是你得到的。
如果您使用例如 while 或 do-while 循环代替 goto 语句,则可以解决您的问题。
,如果您使用调试器单步调试代码(或至少打印出一些描述游戏决策的诊断消息),您将确切了解程序终止的原因。
假设 number
为 20
且 answer
为 41
,则 warmer1
为 31
且 warmer2
为 {{1 }},因此:
9
由于 void game() {
...
START:
...
if (answer > warmer2) { // 41 > 9 is TRUE
if (answer == number) { // 41 == 20 is FALSE
...
} else if (answer < warmer1) { // 41 < 31 is FALSE
...
goto START; // <-- NOT REACHED!
}
// <-- execution reaches here!
} else if (answer > number) { // <-- NOT EVALUATED!
...
goto START; // <-- NOT REACHED!
} else if (answer < number) { // <-- NOT EVALUATED!
...
goto START; // <-- NOT REACHED!
}
// <-- execution reaches here!
}
函数没有到达 game()
语句,循环结束并 goto START;
退出,因此 game()
退出,终止程序。
在现代 C++ 编码中几乎没有充分的理由使用 main()
。改用 goto
或 while
循环,例如:
do..while