【发布时间】:2014-02-25 17:01:15
【问题描述】:
我正在尝试编写一个程序,该程序使用一个函数在用户提供的范围内生成 10 个随机数。它似乎工作正常,除了返回的数字都是 1 的事实:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int rand_int(int min, int max);
int main()
{
int min, max;
cout << "Hello user.\n\n"
<< "This program will generate a list of 10 random numbers within a
given range.\n"
<< "Please enter a number for the low end of the range: ";
cin >> min;
cout << "You entered " << min << ". \n"
<< "Now please enter a number for the high end of the range: ";
cin >> max;
while(min > max){
cout << "Error: Your low number is higher than your high number.\n"
<< "Please reenter your high number, or press ctrl + c
to end program.\n";
cin >> max;
cout << endl;
}
for(int i = 0; i < 10; i++){
int rand_int(int min, int max);
cout << rand_int << endl;
}
return 0;
}
int rand_int(int min, int max)
{
srand(time(0)); // Ensures rand will generate different numbers at different times
int range = max - min;
int num = rand() % (range + min);
return num;
}
【问题讨论】:
-
你应该回去阅读变量定义和函数调用。另外,不要每次都重新播种(尤其是不要在紧密循环中使用
time(0))。 -
你能再具体一点吗?我面前有这本书,但并没有具体说明您可以在哪里或如何称呼他们。
-
尝试使用调试器单步调试代码,如果您没有调试器,请在代码中添加打印以显示正在发生的事情。
-
这看起来像是一个家庭作业问题,但我认为您会发现使用调试器逐步执行 rand_int 函数会很有启发性。我会拆分
int num = rand() % (range + min);行,这样您就可以看到那里发生了什么。 (伟大的思想必须以相同的方式思考@brianbeuning) -
这已经解释了countless times on SO,但不要使用模运算来限制RNG的输出范围。你会扭曲结果的分布。此外,用
time (0)播种RNG 对您没有任何好处——time (0)的粒度为1 秒。如果您经常调用rand_int (...),您基本上是在重新播种具有相同值的 RNG。