Problem with rand() in C [duplicate]

会有一股神秘感。 提交于 2020-07-08 18:57:53

问题


Possible Duplicate:
why do i always get the same sequence of random numbers with rand() ?

This is my file so far:

#include <stdio.h>

int main(void) {
    int y;
    y = generateRandomNumber();
    printf("\nThe number is: %d\n", y);
    return 0;
}

int generateRandomNumber(void) {
    int x;
    x = rand();
    return x;
}

My problem is rand() ALWAYS returns 41. I am using gcc on win... not sure what to do here.

EDIT: Using time to generate a random number won't work. It provides me a number (12000ish) and every time I call it is just a little higher (about +3 per second). This isn't the randomness I need. What do I do?


回答1:


you need to provide it a seed.

From the internet -

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
  int i, stime;
  long ltime;

  /* get the current calendar time */
  ltime = time(NULL);
  stime = (unsigned) ltime/2;
  srand(stime);

  for(i=0; i<10; i++) printf("%d ", rand());

  return 0;
}



回答2:


Standard trick is:

srand(time(0));  // Initialize random number generator.

NOTE: that function is srand, not rand.

Do this once in your main function. After that, only call rand to get numbers.

Depending on the implementation, it can also help to get and discard a few results from rand, to allow the sequence to diverge from the seed value.




回答3:


Try calling srand(time(NULL)); before your call to generateRandomNumber.

As others have stated, you need to call srand() one time when the application starts up, not every time that you call rand().




回答4:


This is because rand() is implicitly seeded to 1.

If you don't want the same sequence of numbers each time you run your program, you should set the seed (using srand()) when the program starts, with a value that changes from one run to another.

The clock time is a popular choice for this, but bear in mind that this is predictable, and could therefore be a vulnerability if you want your number sequence to be unpredictable.




回答5:


Sometimes compilers use the same random seed to help debugging easier which is great but defeats the purpose of randomize. There are code examples on how to seed your random generator with some dataset, usually system time but this is the explanation behind why you got the same number over and over.




回答6:


as before, a seed. Often times something like, time() or pid()



来源:https://stackoverflow.com/questions/1190689/problem-with-rand-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!