0

I have one piece of code that is giving me some trouble and is confusing.

Here is the piece of code...

int r = rand() % 100;
printf("Random number: %u", r);

Why does it print 7 every time? According to the book it should print any number 0-100 I believe... am I wrong with this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dummy Code
  • 1,858
  • 4
  • 19
  • 38

2 Answers2

11

You have to seed it first:

srandom(time(NULL));

It is actually better to just use arc4random:

int r = arc4random() % 100;
printf("Random number: %u", r);
sosborn
  • 14,676
  • 2
  • 42
  • 46
  • Ah... Thank you. That was successful. Why is arc4random better? Just preference or is the delegate just better? – Dummy Code May 17 '13 at 01:55
  • Or is it just easier this way? Thanks for the quick answer. – Dummy Code May 17 '13 at 01:57
  • 5
    `srandom` is for seeding `random`. Use `srand` to seed `rand`. And it is better to use `arc4random_uniform` instead of `arc4random` when you will be apply modulus to the result (like is being done here). – rmaddy May 17 '13 at 02:06
2

Random numbers are pseudo-random. To make them seem random, they are seeded at arbitrary times based on your design. If you want seeding and "random" number generation to happen simultaneously, use arc4random instead, which also provides other benefits.

Jerome Baldridge
  • 518
  • 2
  • 13