【问题标题】:Random number generator not generating within set variable parameters随机数生成器不在设置的变量参数内生成
【发布时间】:2017-09-10 20:55:33
【问题描述】:

如果这是一个简单的问题,请原谅我,我对编码非常陌生,但我一直在尝试创建一个程序,在该程序中,用户会想到一个数字,而计算机会尝试使用随机参数来猜测它数发生器。

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

using namespace std;

int main()
{
    srand(static_cast<unsigned int>(time(0))); //seed random number generator
    int guess = (rand() % 100) + 1; //random number between 1 and 100
    int turns = 1;
    int max = 100;
    int min = 1;

    cout << "Pick a number between 1 and 100 then press enter." << endl;
    cin.get();

    string responce = "n";
    cout << "Was " << guess << " your number? Y/N" << endl;
    cin >> responce;

    while (responce == "n" || responce == "N")
    {
        ++turns;

        string lowresponce;
        cout << "Was the number too low?" << endl;
        cin >> lowresponce;

        if (lowresponce == "y" || lowresponce == "Y")
        {
            min = guess; //this statement should (?) set the minimum number to whatever was guessed.
            guess = (rand() % max) + min; //then this should calculate a number between the minimum (which is the last number guessed) and the maximum
        }
        if (lowresponce == "n" || lowresponce == "N")
        {
            max = guess;
            guess = (rand() % max) + min;
        }

        cout << "Was " << guess << " your number? Y/N" << endl;
        cin >> responce;
    }

    cout << "I guessed your number, " << guess << ", in " << turns << " turns!" << endl;

    return 0;
}    

偶尔会在设置的参数之外生成一个数字,像这样, 对于我的生活,我无法理解为什么。

试运行结果:

数字 = 60

第一次猜测 = 72,最大值设置为 72

第二次猜测 = 39,最小值设置为 39

第三次猜测 = 45,最小值设置为 45

第 4 次猜测 = 99,超出范围 (45,72),并且一开始不应该是猜测。

关于为什么会发生这种情况的任何想法?

【问题讨论】:

  • 它不应该是guess = (rand() % max) + min;,因为它可以给出一个从min到min+max-1的随机数;

标签: c++ random


【解决方案1】:

想想看,你选择了 60,计算机猜测为 30。所以你设置 min = 30(正确),并且你希望你的范围是 (30,100]。所以你应该设置:

guess = (rand() % (max - min)) + min;

相同的计算,更大的猜测

编辑:为了改进你的代码,我建议你学习do while,它可能会有所帮助:)

【讨论】:

    【解决方案2】:

    我意识到这并不完全是在回答这个问题,但你真的不应该像你那样生成随机数。从 C++11 开始,您应该使用 MT 生成器,它更易于使用和理解。

    std::random_device rd;
    std::mt19937 rng(rd());
    std::uniform_int_distribution<int> uni(0, 100);
    
    int foo = uni(rng);
    

    【讨论】:

      猜你喜欢
      • 2010-12-10
      • 1970-01-01
      • 2023-01-03
      • 2018-01-01
      • 1970-01-01
      • 2014-09-20
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多