这个C ++猜测游戏在语法上是否正确?

时间:2013-09-21 04:59:21

标签: c++ random

#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,因为它没有我需要的输入系统来运行这个程序。我不得不很快将它提交给一个班级,但考虑到我的大盘(我的所有软件都存储在那里)昨晚被破坏了。
我为这个问题的愚蠢道歉。

2 个答案:

答案 0 :(得分:1)

是的,语法正确,但不合逻辑,由于

bool isCorrect = true;

阻止循环启动,它应该是

bool isCorrect = false;

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

答案 1 :(得分:0)

程序中有两个逻辑错误:

  1. 游戏根本不会运行,因为isCorrect最初是真的。
  2. 随机数生成器未获取种子,因此rand()将在每次运行时返回相同的值,randomint始终相同。您应事先致电srand( seed ),其中seed是无符号的(例如time(0))。*
  3. *实际上,如果你不这样做,你的游戏仍会运行,但在第一次尝试后很容易被击败

相关问题