随机数和编程逻辑

时间:2015-01-02 05:21:46

标签: c++ random srand

我在下面的作业中遇到了麻烦。

“编写一个生成1-100之间随机整数的程序,然后要求用户猜出该数字是什么。如果用户的猜测高于随机数,程序应显示”太高,再试一次。 “如果用户的猜测低于随机数,程序应显示”太低,再试一次。“程序应该使用循环重复,直到用户正确猜到随机数。”

如何使随机数工作,是否有更好/更有效的方式来编写任何部分?我还在学习C ++

这是我的代码

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

int main()
{
    // declare variables
    int rightAnswer, userAnswer;

    // determine rightAnswer
    srand (time(NULL));
    rightAnswer = (rand() % 100) + 1;

    // begin the game
    cout << "I'm thinking of a number between 1-100!" << endl;
    do{
        // collect data
        cout << "Guess: ";
        cin >> userAnswer;

        // if else statements to determine correctness
        if (userAnswer < 1 || userAnswer > 100)
            cout << "The number is in the range 1-100. Try again!" << endl;
        else if (userAnswer > rightAnswer)
            cout << "Too high! Try again!" << endl;
        else if (userAnswer < rightAnswer)
            cout << "Too low! Try again!" << endl;
        else
            cout << "That's it! Good job!" << endl << ":)";


    } while (userAnswer != rightAnswer);
    return 0;
}

1 个答案:

答案 0 :(得分:6)

中,您可以使用Random number distributions的正确选择在给定范围内更均匀地生成随机数。均匀分布使用的一个示例如下所示:

#include <random>

...
std::random_device rd; // obtain a random number
std::mt19937 engine(rd());
std::uniform_int_distribution<> distribution(1, 100); // define the range

const int rightanswer = distribution(engine);
相关问题