请原谅我,如果这是一个简单的问题,我对编码非常陌生,但我一直在尝试创建一个程序,用户会想到一个数字而计算机会尝试使用随机数发生器上的参数。
#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),并且不应该首先猜测。
有关为何发生这种情况的任何想法?
答案 0 :(得分:0)
想想看,你选择60,计算机猜测30.所以你设置min = 30(正确),你希望你的范围是(30,100)。所以你应该设置:
guess = (rand() % (max - min)) + min;
更大猜测的相同计算
编辑:为了改进您的代码,我建议您学习do while
,这可能会有所帮助:)
答案 1 :(得分:0)
我意识到这并不完全是回答这个问题,但你真的不应该像你那样生成随机数。从C ++ 11开始,你应该使用MT生成器,它更容易使用和理解。
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<int> uni(0, 100);
int foo = uni(rng);