Hi.

Before you say anything, I have read the FAQ, but I am very new to coding (atleast C++) and it didn't help much.

How do I make a random number, say.... a number from 1-5??

Printable View

- 09-16-2001UnregisteredRandom Numbers
Hi.

Before you say anything, I have read the FAQ, but I am very new to coding (atleast C++) and it didn't help much.

How do I make a random number, say.... a number from 1-5?? - 09-16-2001taylorguitarman
2

there you go.

wait

5

no no.

1

feel free to use me as your random number generator anytime. - 09-16-2001taylorguitarman
seriously.

srand(a_number) function will seed your number generator.

then use rand() anytime you need a random number.

to get it between two numbers try this: I pulled it from a book but have not tried it.

random_number = (rand() % (max + 1 - min) + min); - 09-16-2001taylorguitarman
it works.

- 09-17-2001face_master
but this gives the same "random" number each time the program is executed. How is it done so it gives a new number each time?

- 09-17-2001taylorguitarman
for a start:

srand( (unsigned)time(0) );

that uses time as you're "random" seed thus making the seed number different each time. If you need truly random numbers you'll have to read up on the topic. - 09-17-2001Brown Drake
Make sure you use srand to seed the rand function. srand is only called once (don't include it in a loop, for example). Rand() can be in a loop though. You can enter a number for srand, but that'll result in the same random numbers if the same number is entered. Seed with the time function in <ctime>.

Code:`srand(time(0));`

.

.

.

x = y + rand() % z;

Code:`num = 1 + rand() % 6;`

- 09-17-2001UnregisteredQuote:

num = 1 + rand() % 6;

- 09-17-2001UnregisteredQuote:

num = 1 + rand() % 6;

1000 % 6 = 4

because:

1000 / 6 = 996 R 4

This will give you a range between 0 and 5. To make it 1 through 6 we add 1 to the equation. - 09-17-2001Unregistered
This is my code...

Code:`#include <iostream.h>`

srand();

int main()

{

int number;

number=1+rand()%6;

cout<<number;

return 0;

}

- 09-17-2001zen
See the above posts, you need to seed the rand function.

#include <ctime>

//In main - you can't call functions globally

srand( (unsigned)time(0) ); - 09-17-2001Unregistered
Yay!! It works.

Thank-you all for your help, I'm very new to C++. - 09-17-2001Brown Drake
Also, if you want your random number to be between 1 and 5, per your first post, change ...rand() % 6 to ...rand() % 5.

- 09-20-2001Unregistered
You people are so gay, here goes the easy way.

#include <stdlib.h>

#include <stdio.h>

#include <conio.h>

#include <iostream.h>

void main()

{

clrscr();

randomize(); //initiates the random function

int x=random(5); // generates a random number b/w 1-5

cout << x;

getch();

}