2

How do I make a random integer value in C? I need it to act like a coin flipping. Here is what I've tried:

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

int main(void)
{
    int i;

    srand(time(NULL));

    for (i=0; i<10; i++)
        if ((int)(((float) rand() / ((float) SHRT_MAX)) * 2) > 0)
            puts("etz");
        else
            puts("pali");
    return EXIT_SUCCESS;
}
iBug
  • 35,554
  • 7
  • 89
  • 134
The Shwarma
  • 180
  • 1
  • 11

1 Answers1

4

The problem with your solution is rand() always returns a positive integer so the expression (int)(((float) rand() / ((float) SHRT_MAX)) * 2) > 0 is always true except on platforms where short and int are the same width.

Another problem is that rand() returns a value from zero to RAND_MAX not SHRT_MAX - it is unlikely in a modern library that RAND_MAX == SHRT_MAX

Your solution may be adapted thus:

(float)rand() / RAND_MAX > 0.5f

but the casting and floating point comparison is unnecessary and over complex, it can be tested thus:

rand() > RAND_MAX / 2 

It is likely to be suggested that you could just test for odd/even with:

rand() % 2 == 0 

but that is problematic in some poorly implemented algorithms because it relies on the randomness of a single LSB - it is likely to work in a modern library, but best avoided to ensure code portability.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Clifford
  • 88,407
  • 13
  • 85
  • 165