Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
Solved

# How do I use random integer generators?

Posted on 1998-10-30
Medium Priority
169 Views
I'm trying to make a program that simulates dice rolling, but I don't know how to use what header files to include, or what commands I need to use.
0
Question by:Jelo
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 4

Accepted Solution

ID: 1176623
To simulate a dice, you need random nos ranging from 1 to 6. You can try the following:

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

int yourfunction(){
//obtain random no seed - using time so that different nos are generated each time
srand( (unsigned)time( NULL ) );
i=(rand()%6)+1;
//i will now contain randomly generated nos from 1 to 6
return i;
}

Hope this will help.
Thanks
0

Author Comment

ID: 1176624
Thaks for the help, but you could explain, in detail, what each part of the function does?
0

LVL 4

Expert Comment

ID: 1176625
The srand() function is used to generate a random number. I am providing the time() function so that the seed will be different each time.
The rand() function generates random numbers based on the seed from 0 to, I think RAND_MAX.
Obtaining the remainder (using %6), I will get an integer between 0 and 5 to which I add 1 to ensure that the value is between 1 and 6.
Thanks,
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
###### Suggested Courses
Course of the Month9 days, 6 hours left to enroll