c语言---srand(time(NULL))产生的随机数一样

测试程序时看到srand(time(NULL))产生的随机数的结果是一样的,便在想为什么,程序测试结果如下:

#include<stdio.h>
#include<stdlib.h> //提供srand() rand()
#include<math.h>   //提供round() pow()
#include<time.h>   //提供time(NULL)
void round2();     //除法:四舍五入保留整数位
void round3();     //除法:c语言中round函数的用法  round函数只有一个参数 有两个参数的不是c语言
int main()
{
    round2();

    round3();

    return 0;
}
void round2()
{
    int a,b;
    int c;

    srand(time(NULL));

    a=rand()%100-50;
    b=rand()%100+1;

    if(a>=0)
    {
        c=(a+b/2)/b;
    }
    else
    {
        c=(a-b/2)/ b;
    }

    printf("\n%d/%d=%d\n",a,b,c);
}

void round3()
{
    int a,b;
    double c;

    srand(time(NULL));

    a=rand()%100-50;
    b=rand()%100+1;

    c=round((double)a/b);

    printf("\n%d/%d=%.0lf\n",a,b,c);
}


测试结果:
 -26/99=0
 -26/99=-0
 Process returned 0 (0x0)   execution time : 0.358 s
 Press any key to continue.

srand(time(NULL))的办法产生随机数,但是time(NULL)产生的时间是以秒为单位,如果程序循环在一秒钟之内执行完,那么time(NULL)每次返回的时间也就是一样的,所以造成srand(time(NULL))每次取的种子也都一样。

大家可以看到这个测试程序的时间是0.358s!!!

所以这个程序中srand(time(NULL))产生的随机数是一样的。

发布了34 篇原创文章 · 获赞 38 · 访问量 2638

猜你喜欢

转载自blog.csdn.net/qq_43779149/article/details/104464697