How to make a random integer?

I want the program to generate a random integer between one and twenty, but I don't know how someone could go about it...any suggestions?
hey dingo25, well to make a random integer you have to include the rand(); command but you have to first make a random number generator which you can do by simply putting randomiize(); usually at the top of your main. Look at my code for more instructions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//Random # Generator Program

#include <stdlib>
#include <iostream>
#include  <conio>
using namespace std;

int main()
{randomize(); //<--- This will initialize a random number generator based on your
              //     local time
int x;
x=rand()%20+1;    //<--- This will display a random number from
cout<<"x="<<x;    // 1-20 because rand()%x is any number from 0 to (x-1)
getch();
return 0;
}


Or You could click on this URL for more instructions on random #'s.
http://www.cplusplus.com/reference/cstdlib/rand/
Pretty sure randomize() isn't a standard function and isn't supported on all compilers.

I suggest the classic way
1
2
3
4
5
6
7
#include <ctime>
using namespace std;

int main()
{
	srand(time(0));  // Creates a seed for the random number to be based on
}
How exactly would I use the seed to say choose a number specifically 1 to 20? And then how would I cout that?
closed account (18hRX9L8)
1
2
3
4
5
6
7
8
9
10
11
12
13
/* created by usandfriends */
#include <iostream>
using namespace std;

main()
{
     int number;

     number=rand() % 20 + 1;
     cout<<number<<endl;
     getchar();

}
Last edited on
Thanks!
Topic archived. No new replies allowed.