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

后端 未结 4 730
陌清茗
陌清茗 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:39

    You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()

    For example

    srand(time(NULL));
    rand();//now returns a random number
    

    The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.

    So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.

提交回复
热议问题