1

I am currently using these functions in C++ to find a number and a suit for a card.

  int getnumber () {
             srand(time(0));
             int number ;
             number = rand()% 13 + 1;
             return number;
             };

         int getsuitn () {
             srand(time(0));
             int suitn;
             suitn = rand() % 4 + 1;
             return suitn;
             }

the output is always just the default constructor for the class, I have all the libraries needed to make this work, what am I doing wrong?

  • 3
    I can't recall how many times I see this problem in SO – Bryan Chen Mar 24 '14 at 03:34
  • @BryanChen can you point to a duplicate? – Floris Mar 24 '14 at 03:39
  • @Floris here are some: http://stackoverflow.com/questions/3159644/using-rand-to-generate-a-random-numbers , http://stackoverflow.com/questions/1068350/random-number-function-is-misfiring most of them are closed/deleted so you can't see them anymore – Bryan Chen Mar 24 '14 at 03:46
  • I'm with you, @BryanChen - I would say that the majority of posts I have seen complaining of "something" wrong with random number generation are caused by seeding the generator in the wrong place. – paddy Mar 24 '14 at 03:50
  • @BryanChen - thanks: I flagged as duplicate. – Floris Mar 24 '14 at 04:07

2 Answers2

3

With the same seed the same sequence will be generated every time. Since you seed with the current time in seconds, every call you make in the same second will get the same first number from the sequence. Your whole program probably runs in under a second, so they all get the same result.

Seed the random number generator once at the start of your program.

Ben Jackson
  • 90,079
  • 9
  • 98
  • 150
0

Question: are you using c++11?

You should use <random> header. These functions will be mostly deprecated in C++14. An example of how to use <random>:

cppreference example

Germán Diago
  • 7,473
  • 1
  • 36
  • 59