1、c语言生成随机数
需要的头文件:#include<stdlib.h>
#include<time.h>
需要使用的函数:rand()、srand()、time()
rand()函数的使用
int n = rand();
生成一个随机数n
接下来,来点更灵活的,让n的取值在-5~55之间:
于是我们想到了用取模,0<= n%61 <=60,n%61减5,得 -5<= n%61-5 <=55,则
int x = n%61-5; // 等价于 int x = rand()%61-5;
生成-5~55范围内的随机数x,其它任何范围同理。
srand()和time()函数的使用
上述生成的随机数每次运行都是相同的,并非是真正意义上的随机数,要生成真正意义上的随机数需要1.2中两个函数的辅助。srand()是种子函数,1.1中未调用该函数,系统默认种子数为1,所以每次运行都是同一个值。time()是调用系统时间的函数。
生成真正意义上的随机数代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
srand(time(0));
int x = rand()%61-5;
return 0;
}
2、c++生成随机数
c++生成随机数和c同理,只要改一下头文件即可,代码如下:
#include<iostream>
#include<cstdlib>
#include<ctime>
int main()
{
srand(time(0));
int x = rand()%61-5;
return 0;
}
原文链接: https://www.cnblogs.com/godfriend/p/10782632.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/294320
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!