Dice rolling function - comparing random number to a value does not work

Hi everyone!
This is my first post here and actually my third tiny program that I am trying to write; I am completely new to C++ and programming in general.

I want to simulate throwing a dice which I have seen can be done in many different ways. The first way I thought of is as shown below, where you first generate a random number between 0 and 1, and then assign values from 1 to 6 to the random number found, where anything below 1/6 gets evaluated to 1, anything between 1/6 and 2/6 gets evaluated to 2, etc.

The random number generation seems to work, but my main function now just returns 5 times the random number that was generated, and then the number '6'. I think the problem is in comparing the 'double' from the random generation to the values, but I cannot seem to get it fixed. There may be an easier way to simulate a dice but I'd really like to know why this one below does not work because it seems logical to me.

Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<stdlib.h>
using namespace std;


//Function rnd() produces a random number between 0 and 1.
int rnd()
{
  srand (time(NULL));
  double random = ((double)rand()/(double)(RAND_MAX));
  cout << random << endl;
    }

int main()
{
  int answer=0;
  if (rnd()<=(1/6)){answer=1;}
  else if (rnd()<=(2/6) && rnd()>(1/6)){answer=2;}
  else if(rnd()<=(3/6) && rnd()>(2/6)){answer=3;}
  else if(rnd()<=(4/6) && rnd()>(3/6)){answer=4;}
  else if(rnd()<=(5/6) && rnd()>(4/6)){answer=5;}
  else {answer=6;}
  cout << answer << endl;
}
1
2
3
4
5
6
if (rnd()<=(1/6)){answer=1;}
  else if (rnd()<=(2/6) && rnd()>(1/6)){answer=2;}
  else if(rnd()<=(3/6) && rnd()>(2/6)){answer=3;}
  else if(rnd()<=(4/6) && rnd()>(3/6)){answer=4;}
  else if(rnd()<=(5/6) && rnd()>(4/6)){answer=5;}
  else {answer=6;}
Each rnd() call will yield a new random value. In addition 1/6, 2/6... are 0 (integer division)
Thanks! Yes indeed that was a silly mistake they are all 0.. I just noticed I made another mistake which was I forgot to put ' return random; ' in the first function which made the whole things evaluate to '6' every time
Topic archived. No new replies allowed.