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
  • 242,098
  • 41
  • 402
  • 602
samir
  • 709
  • 2
  • 7
  • 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
  • 246,832
  • 83
  • 321
  • 542
0

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

Ed Heal
  • 57,599
  • 16
  • 82
  • 120
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,517
  • 2
  • 19
  • 29