Why do I get the same result with rand() every time I compile and run?

后端 未结 4 776
陌清茗
陌清茗 2020-11-27 07:47

Whenever I run this code, I get a same result.

Program

#include

int main(int agrc, const char *argv[]) {
 int i = rand();
 printf(\"         


        
4条回答
  •  囚心锁ツ
    2020-11-27 08:43

    The output from rand is pseudo-random, which means that it looks effectively random, but is computed the same way each time, starting from a special value called the seed. With the same seed value, you get the same sequence of random numbers.

    To set a different seed, use the standard C function void srand(unsigned int) once in your code before you start generating random numbers. One common way of getting a different sequence of random numbers each time you run the program is to base the seed on the clock time. E.g. srand(clock())

提交回复
热议问题