首页 > 解决方案 > C++ 随机 srand 代码 - 如果 else 不给出正确的结果

问题描述

我没有收到对我的代码的正确响应。当我输入正确的数字时,它应该给出“优秀”;但是,它总是输出“不正确” - 请提出建议。

#include <iostream>
#include <ctime>
using namespace std;

int guess()
{
    int x = 0;
    x = 1 + rand() % 1000;
    return x;
}

int main()
{
    int input = 0;
    srand( time( 0 ) );
    cout << guess() << endl;
    cout << "I have a number between 1 and 1000. " << endl;
    cout << "Can you guess my number? " << endl;
    cout << "Please type your first guess. " << endl;
    cin >> input;

    if (guess() == input)
        cout << "Excellent! You guessed the number! " << endl;
    else
        cout << "Incorrect! " << endl;

    system ("pause");
    return 0;
}

标签: c++

解决方案


您调用了两次 function guess(),因此每次运行时它可能会为您提供不同的值。您必须存储该值,然后将其与原始值进行比较。


推荐阅读