random or rand function prints the same value, even in different machines

前端 未结 3 1365
深忆病人
深忆病人 2021-01-06 21:26

I want to print a random number in the range 1 to 6. I have the following code.

printf(\"The random value is %d \\n\",random(6));

It is pri

3条回答
  •  无人及你
    2021-01-06 21:44

    First of all, random() does not take any arguments.

    Secondly, from the fine manual:

    Like rand(), random() shall produce by default a sequence of numbers that can be duplicated by calling srandom() with 1 as the seed.

    So, unless you explicitly specify a seed by calling srandom(), random() will produce the same sequence of values every time.

    Thirdly, random() returns a long so you should be using %ld in your printf() call.

    Fourthly, learn about your compiler's warning flags, turn them all on, and pay attention to their output. You can turn off some of the warning flags once you understand why it is safe to do so.

提交回复
热议问题