【发布时间】:2021-07-20 19:30:32
【问题描述】:
我试图做一个简单的猜数字游戏,当答案大于数字时,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;
}
谁能帮忙解决一下谢谢!!!
【问题讨论】:
-
goto?do..while循环会更合适。如果您立即system("clear")显示,打印出number有什么意义? -
哪个
if/else不会“触发”?第一个?其他人之一?输入是什么?输出是什么?在调试器中单步执行程序时发生了什么? -
第二个 if/else 没有触发。
-
请不要使用
goto -
@DiazMichael "它是来自函数的随机数生成器。 minimal reproducible example.
标签: c++ if-statement goto