网站内容和功能清单,宁波企业网站建站,手机软件开发外包,附近电脑培训速成班一个月转载自**
https://www.cnblogs.com/ql698214/p/5424937.html
** 一、使用rand()函数 头文件stdlib.h
(1) 如果你只要产生随机数而不需要设定范围的话#xff0c;你只要用rand()就可以了#xff1a;rand()会返回一随机数值, 范围在0至RAND_MAX 间。RAND_MAX定义在s…转载自**
https://www.cnblogs.com/ql698214/p/5424937.html
** 一、使用rand()函数 头文件stdlib.h
(1) 如果你只要产生随机数而不需要设定范围的话你只要用rand()就可以了rand()会返回一随机数值, 范围在0至RAND_MAX 间。RAND_MAX定义在stdlib.h, 其值为2147483647。
例如
#includestdio.h
#includestdlib.h
void main()
{for(int i0;i10;i)printf(%d/n,rand());
}(2) 如果你要随机生成一个在一定范围的数你可以在宏定义中定义一个random(int number)函数然后在main()里面直接调用random()函数
x rand()%11; /产生1~10之间的随机整数/
y rand()%51 - 25; /产生-25 ~ 25之间的随机整数/
z ((double)rand()/RAND_MAX)*(b-a) a;/产生区间[a,b]上的随机数/
#includeiostream
#includestdlib.husing namespace std;#define random(x) (rand()%x)void main() { for (int i 0; i 10; i) {cout random(10) ;}cout endl;system(pause);
}(3)但是上面两个例子所生成的随机数都只能是一次性的如果你第二次运行的时候输出结果仍和第一次一样。这与srand()函数有关。srand()用来设置rand()产生随机数时的随机数种子。在调用rand()函数产生随机数前必须先利用srand()设好随机数种子seed, 如果未设随机数种子, rand()在调用时会自动设随机数种子为1。上面的两个例子就是因为没有设置随机数种子每次随机数种子都自动设成相同值1 进而导致rand()所产生的随机数值都一样。
srand()函数定义 void srand (unsigned int seed);
通常可以利用geypid()或time(0)的返回值来当做seed如果你用time(0)的话要加入头文件#includetime.h
#includeiostream
#includestdlib.h
#includetime.husing namespace std;#define random(x) (rand()%x)void main() { srand((int)time(0));for (int i 0; i 10; i) {cout random(10) ;}cout endl;system(pause);
}1 4随机产生a,b)区间内的随机数
#includeiostream
#includestdlib.h
#includetime.h
#includeiomanip
using namespace std;
#define random(a,b) (((double)rand()/RAND_MAX)*(b-a)a)void main() { srand((int)time(0));for (int i 0; i 100; i) { cout random(0, 10) ;}cout endl;system(pause);
}1 5四舍五入返回整数通过floor和ceil函数实现
#includeiostream
#includestdlib.h
#includetime.h
#includeiomanip
using namespace std;/*四舍五入返回整数*/
double round(double r)
{return (r 0.0) ? floor(r 0.5) : ceil(r - 0.5);
}
double randomRange(double a, double b)
{ double x (double)rand() / RAND_MAX;double result x*(b - a) a;return round(result);
}void main() { srand((int)time(0));for (int i 0; i 100; i) {//cout fixed setprecision(0) randomRange(0, 10) ;cout randomRange(0, 10) ;}cout endl;system(pause);
}henry 好文要顶 关注我 收藏该文