random function; first ouput way too high

i'm looping a random function to get random numbers from a die. the first number is always way too high. can someone please indicate where i'm going wrong.

6422352
1
2


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 int die()
{
     int result = (rand()% 6+1);
     return result;

}

int main()
{
    srand(time(NULL));
    
for(int i=0; i<=2; i++)//position of players!=boardSize(a)
    {
        int res = die();
        cout<<res<<endl;
    }
}
Last edited on
Once I put the headers in
1
2
3
4
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

it produced
5
2
3


So, no problems then.
Using modern C++ (C++11 or later) to generate random numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <random>   // http://www.cplusplus.com/reference/random/

int die();

int main()
{
   for (int i { }; i < 3; ++i)
   {
      std::cout << die() << ' ';
   }
   std::cout << '\n';
}

int die()
{
   // create a prng, using the default imp
   // seeded with a deterministic random engine
   static std::default_random_engine prng(std::random_device {} ());

   // create a distribution to simulate a 6 sided die
   static std::uniform_int_distribution<int> dis(1, 6);

   // simulate a die throw and return it
   return dis(prng);
}

5 1 6

Sure, for really trivial uses like this example using <random> looks more complicated than using the C library. But using the C library in C++ apps is not recommended. Even the C standard recommends not using srand/rand if there are alternatives available.

https://web.archive.org/web/20180123103235/http://cpp.indi.frih.net/blog/2014/12/the-bell-has-tolled-for-rand/

https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
Topic archived. No new replies allowed.