Solved

How do I use random integer generators?

Posted on 1998-10-30
3
157 Views
Last Modified: 2010-04-02
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
Comment
Question by:Jelo
  • 2
3 Comments
 
LVL 4

Accepted Solution

by:
pagladasu earned 50 total points
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
Pagladasu
0
 

Author Comment

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

Expert Comment

by:pagladasu
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,
Pagladasu
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now