c language --- srand (time (NULL)) of the same random number generator

See srand (time (NULL)) the results of random number generation is the same, they wonder why, when the test program testing program results are as follows:

#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)) approach to generating a random number, but the time time (NULL) generated is in seconds, if the program cycle be executed within one second, then the time (NULL) return each time also is the same, so the resulting srand (time (NULL)) each seed taken are the same.

We can see that this time the test program is 0.358s! ! !

Therefore, the random number in the program srand (time (NULL)) produced is the same.

Published 34 original articles · won praise 38 · views 2638

Guess you like

Origin blog.csdn.net/qq_43779149/article/details/104464697