C++产生随机数的问题~~~

来源:百度知道 编辑:UC知道 时间:2024/05/30 22:39:31
到底怎么产生随机数啊~~~跪求高手解释清楚一点

#include<stdlib.h>
main()
{
int i,j;
for(i=0;i<10;i++)
{
j=1+(int)(10.0*rand()/(RAND_MAX+1.0));
printf("%d ",j);
}
}

为什么提示
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

error C3861: 'printf': identifier not found?

提示'printf': identifier not found?

是因为你没有include<stdio.h>

另外一个错是因为你的main()函数没有标记类型,写成void main()就好了。

如果要产生随机数,先include<time.h>,然后程序开始的地方,也就是main()里面一开头,先srand(time(0));一次,(不写这个的话每次开程序随机数都一样,这是种子,你就理解成计算机利用现在的时间来生成随机数就好了)以后随便用rand()函数了。比如你需要的到1~100之间的随机数,就写rand()%100; 如果需要200~345之间的函数,就写200+rand()%145就好了。

#include<ctime>
……
srand(time(0));//time(0)是种子,自己选择一个数也可以,但最好设置为rank(),这样随机性会比较好
int x = rand();
……

#include <iostream.h>
#include <stdio.h>
#include <time.h>
main()
{int a;
srand(time(0));
a=rand()%100;
cout<<a<<endl;
}