0

This is my code

 #include <stdio.h>
 #include <stdlib.h>


 main()
 {
    int r = rand() % 20;
    printf("%d", r);
 }

I want to get a random number 19 and below, but it just gives me 1 every time I compile and run it. Can someone show me what I am doing wrong?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
samir
  • 759
  • 2
  • 8
  • 13

3 Answers3

1

Try

#include <stdio.h>
#include <stdlib.h>


 int main()
 {
    srand(time(NULL));
    int r = rand() % 20;
    printf("%d", r);
 }

Note: Using the % is not a great way to get an even distribution.
See: Recommended way to initialize srand? for more info.

Community
  • 1
  • 1
Martin York
  • 257,169
  • 86
  • 333
  • 562
0

Read up about seeding the random number generator - i.e. http://linux.die.net/man/3/srand

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

If you are using Turbo C++ 4.5 then put a

randomize();

before

int r=rand()%20;

It will also give your desired result.

user2100721
  • 3,557
  • 2
  • 20
  • 29