im having trouble creating a random number generator (like say a dice rolling game) if anyone could possibly show me some code for a random number generator that would be greatly appriciated :mrgreen:

Show us what you have. You using rand()?

Simple solution:

``````Randomize(); //Required in Borland C++

//Generate a random number between 1 and 6
int random_number = (rand() % 6) + 1;``````

Andi

>> Randomize(); //Required in Borland C++

``````#include <cstdlib>
#include <ctime>
#include <iostream>

int main()
{
std::srand(static_cast<unsigned>(std::time(0)));

// Generate 10 rolls of a 6 sided die
for (int i = 0; i < 10; i++)
std::cout << std::rand() % 6 + …``````

## All 11 Replies

Show us what you have. You using rand()?

well i tried to switch a java dice rolling program to C++ but that had ALOT of problems so i scraped that code and havent been able to figure anything else out yet :sad:

Simple solution:

``````Randomize(); //Required in Borland C++

//Generate a random number between 1 and 6
int random_number = (rand() % 6) + 1;``````

Andi

>> Randomize(); //Required in Borland C++

``````#include <cstdlib>
#include <ctime>
#include <iostream>

int main()
{
std::srand(static_cast<unsigned>(std::time(0)));

// Generate 10 rolls of a 6 sided die
for (int i = 0; i < 10; i++)
std::cout << std::rand() % 6 + 1 << '\n';
}``````

On some older compilers, using modulus with rand will give you horrible sequences unless the value comes close to RAND_MAX, in this case 6 isn't even close to close. ;) So you'll see this trick as a workaround:

``````#include <cstdlib>
#include <ctime>
#include <iostream>

int main()
{
std::srand(static_cast<unsigned>(std::time(0)));

// Generate 10 rolls of a 6 sided die
for (int i = 0; i < 10; i++) {
int r = int((double(std::rand()) / RAND_MAX) * 6 + 1);
std::cout << r << '\n';
}
}``````

There is a good tutorial on this site you just have to search for it :D

thanks this will help me move faster in my master plan (my game) :D

hi,
I think that the below function will help you to generate random number betwwen any two numbers you want .

``````/*Decleration of random_range function */

int random_range (int lowest_no ,int highest_no ) {
int range ;
int rando;
if (lowest_no > highest_no )
{  int temp =lowest_no ;
lowest_no =highest_no ;
highest_no =temp ;
}

range =highest_no -lowest_no +1;
rando =(range *rand()/ (RAND_MAX +1));
return (lowest_no +rando );
}``````

<< moderator edit: added [code][/code] tags >>
feda :)

This seams like a good place to post this question, if I want to make some thing that generates a random number out of 1 and 2, how would I check that number? Like I ask the user to enter a number, 1 or 2, and if the user typed in the right number that the random generated some thing happens, and if not some thing else happens. Can some one please give me a few examples of this in C++.

Look up `srand()` and `rand()` . Then use an `if` statement.