gpt4 book ai didi

c++ - 随机数生成器未在设置的变量参数内生成

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:42:48 25 4
gpt4 key购买 nike

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

#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

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

关于为什么会发生这种情况有什么想法吗?

最佳答案

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

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

相同的计算以获得更大的猜测

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

关于c++ - 随机数生成器未在设置的变量参数内生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46145500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com