我想在循环内生成随机数,但结果总是相同的数字
我做错了什么?谢谢。
的代码
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
const char duom[] = "U1.txt";
const char rez[] = "U1_rez.txt";
void num_gen(int & x, int & y);
int main(){
srand(time(NULL));
int x, y;
ifstream fd(duom);
fd >> x >> y;
fd.close();
ofstream fr(rez);
for(int j = 1; j <= 4; j++){
num_gen(x, y);
fr << x << " + " << y << " = "<< x + y << endl;
fr << x << " - " << y << " = "<< x - y << endl;
fr << x << " * " << y << " = "<< x * y << endl;
fr << x << " / " << y << " = "<< x / y << endl;
fr << "************" << endl;
}
fr.close();
return 0;
}
void num_gen(int & x, int & y){
x = 3 + (rand() % 10);
y = 3 + (rand() % 10);
}
结果
4 + 8 = 12
4 - 8 = -4
4 * 8 = 32
4/8 = 0
************
4 + 9 = 13
4 - 9 = -5
4 * 9 = 36
4/9 = 0
************
9 + 11 = 20
9 - 11 = -2
9 * 11 = 99
9/11 = 0
************
12 + 8 = 20
12 - 8 = 4
12 * 8 = 96
12/8 = 1
************
答案 0 :(得分:4)
随着C ++ 11/14的出现,您实际上应该放弃使用srand
&amp; rand
&amp;使用标题#include<random>
中声明的更高效的RANDOM NUMBER GENERATING MACHINES。以一个简单的例子说明: -
#include <iostream>
#include <random> // for default_random_engine & uniform_int_distribution<int>
#include <chrono> // to provide seed to the default_random_engine
using namespace std;
default_random_engine dre (chrono::steady_clock::now().time_since_epoch().count()); // provide seed
int random (int lim)
{
uniform_int_distribution<int> uid {0,lim}; // help dre to generate nos from 0 to lim (lim included);
return uid(dre); // pass dre as an argument to uid to generate the random no
}
int main()
{
for (int i=0;i<10;++i)
cout<<random(10)<<" ";
return 0;
}
上述代码的一个输出是: -
8 5 0 4 2 7 9 6 10 8
请参阅,数字从0到10不等。根据您所需的输出,在uniform_int_distribution
中给出限制。这件事很少失败&amp;你可以在更大的范围内生成随机数,而不必像你那样担心令人发指的输出。
答案 1 :(得分:2)
可能是因为随机方法随着计算机的运行而运行。因此,如果在相同的1/10000秒内,您的计算机执行了他需要执行的所有操作,您可能会读取相同的数字,因为随机方法无法刷新该值。尝试在for
的末尾(如sleep(100)
)进行睡眠,并检查值是否发生了变化。
答案 2 :(得分:1)
我认为你的代码应该生成不同的&#34;伪&#34;每次运行时3到12之间的随机数,只要每次运行之间经过一秒钟。检查这一切是否真的是你想要的。
当你打电话给time(NULL)
时,也许你只是比一秒钟的增加更快地运行它,这会返回自纪元以来的秒数。
无论如何,你的随机数不是很好,因为你使用低阶位。我在rand()
手册页中记录了这段摘录:
In Numerical Recipes in C: The Art of Scientific Computing (William H.
Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New
York: Cambridge University Press, 1992 (2nd ed., p. 277)), the follow-
ing comments are made:
"If you want to generate a random integer between 1 and 10, you
should always do it by using high-order bits, as in
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
and never by anything resembling
j = 1 + (rand() % 10);
(which uses lower-order bits)."