这C++猜谜游戏在语法上是否正确

Is this C++ Guessing Game syntactically correct?

本文关键字:是否 语法 C++ 游戏      更新时间:2023-10-16
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
int min = 1;
int max = 100;
int count = 0;
int randomint = min + (rand() % (int)(max - min + 1));
bool isCorrect = true;
while(!isCorrect){
    int guess = 0;
    cout << "What is your guess? " << endl;
    cin >> guess;
    if(guess < randomint){
        cout << "Too low!" << endl;
        count++;
    } else if (guess > randomint){
        cout << "Too high!" << endl;
        count++;
    } else{
        cout << "Correct!" << endl;
        cout << "Number of Guesses: " << count << endl;
        isCorrect = true;
    }
}
}

新C++编程。 我无法让它编译一个 IDEOne,因为它没有我需要的输入系统来运行这个程序。 我必须尽快提交这个课程,但考虑到我的大磁盘(存储我所有软件的地方)昨晚损坏了。
对于这个问题的愚蠢,我深表歉意。

是的,它在语法上是正确的,但在逻辑上不是,因为

bool isCorrect = true;

防止循环启动,应该是

bool isCorrect = false;

并且像魅力一样工作(但通过例如运行 srand(time(NULL)); 来初始化随机数生成器是合理的)

你的程序在逻辑上有两个错误:

  1. 游戏根本不会运行,因为最初isCorrect是正确的。
  2. 随机数生成器不会获得种子,因此rand()每次运行时都会返回相同的值,并且randomint始终相同。您应该事先致电srand( seed ),其中seed是未签名的(例如time(0))。

*实际上,如果您不这样做,您的游戏仍然可以运行,但是在第一次尝试后很容易被击败