
&&&&有关c语言中随机数函数rand和srand的见解&&&
首先我们要对rand和srand总体认识一下:srand()初始化随机种子,rand()产生随机数,也就是说srand必须要有种子,种子是随机的,而rand可以没有种子,系统会默认为种子为1,言外之意就是srand()随机产生数字,rand()产生固定随机数如果要想再次产生不同随机数需要对种子进行再次赋不同的种子。
示例代码
///////rand()///////
#include<stdlib.h>//stdlib 头文件即standard library标准库头文件,此时需要用到库函数rand或者是srand。
#include<iostream>
using namespace std;
int main()
{
int i,j,a,b;
cout<<"请输入a,即得到随机数为a到a+b"<<endl;
cin>>a>>b;
for(i=0;i<10;i++)
{
j=rand()%b+a;
cout<<j<<" ";
}
return 0;
}
由截图可以看到两次结果一样、这也证明了rand函数产生的随机数为固定数值
///////srand()///////
#include<stdlib.h>//stdlib 头文件即standard library标准库头文件,此时需要用到库函数rand或者是srand。
#include<iostream>
#include<time.h>//包含time函数
using namespace std;
int main()
{
int i,j,a,b;
cout<<"请输入a,b即得到随机数为a到a+b"<<endl;
cin>>a>>b;
srand((int)time(0));
for(i=0;i<10;i++)
{
j=rand()%b+a;
cout<<j<<" ";
}
return 0;
}
这里产生随机数用到了数学中的线性同余法,
线性同余
公式:Xn+1=(xn*a+b)%c即求0-(c-1)范围内的一个伪随机数,可以类比rand函数
此时通过代码我们可以看到rand和srand用法的不同,
Srand比rand即在for循环外多出srand((int)time(0));这条语句。
(int)time(0)即为srand的随机种子
这时可以通过库函数对比两者的不同
然后再来分析(int)time(0)。
这时出现了time_t time( time_t *time );这条语句,那么time_t*time又是什么呢?下面是time reference的解释
函数:time_t time ( time_t * timer );
1 time
Get current time
Get the current calendar time as a time_t object.
The function returns this value, and if the argument is not a null pointer, the value is also set to the object pointed bytimer.
Parameters
timer
Pointer to an object of type time_t, where the time value is stored.
Alternativelly, this parameter can be a null pointer, in which case the parameter is not used, but atime_t object is still returned by the function.
Return Value
The current calendar time as a time_t object.
If the argument is not a null pointer, the return value is the same as the one stored in the location pointed by the argument.
If the function could not retrieve the calendar time, it returns a -1 value.
Example
1 | /* time example */ #include <stdio.h> #include <time.h>
int main () { time_t seconds;
seconds = time (NULL); printf ("%ld hours since January 1, 1970", seconds/3600);
return 0; } |
Possible output:
266344 hours since January 1, 1970 |
2time_t
type
<ctime>
Time type
Type capable of representing times and support arithmetical operations.
This type is returned by the time function and is used as parameter by some other functions of the<ctime> header.
It is almost universally expected to be an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC. This is due to historical reasons, since it corresponds to a unix timestamp, but is widely implemented in C libraries across all platforms.
这里可以看出srand种子和1970-01-01到现在时间的秒数有关.所以说srand产生的随机数是变化的。但是两函数产生的随机数都是为随机数,随机数是通过计算机经过特定的运算产生的一组符合整台分布的数字。这时我们便可以敬爱那个这些数字作为随机数来使用、、