【发布时间】: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的随机数;