Code to generate random numbers in C++

Posted by user1678927 on Stack Overflow See other posts from Stack Overflow or by user1678927
Published on 2012-09-18T01:23:00Z Indexed on 2012/09/19 3:38 UTC
Read the original article Hit count: 142

Filed under:
|
|

Basically I have to write a program to generate random numbers to simulate the rolling of a pair of dice. This program should be constructed in multiple files. The main function should be in one file, the other functions should be in a second source file, and their prototypes should be in a header file. First I write a short function that returns a random value between 1 and 6 to simulate the rolling of a single 6-sided die.Second, i write a function that pretends to roll a pair of dice by calling this function twice. My program starts by asking the user how many rolls should be made. Then I write a function to simulate rolling the dice this many times, keeping a count of exactly how many times the values 2,3,4,5,6,7,8,9,10,11,12(each number is the sum of a pair of dice) occur in an array. Later I write a function to display a small bar chart using these counts that ideally would look something like below for a sample of 144 rolls, where the number of asterisks printed corresponds to the count:

2    3    4    5    6    7    8    9   10    11    12
*    *    *    *    *    *    *    *    *     *     *
*    *    *    *    *    *    *    *    *     *     *
*    *    *    *    *    *    *    *    *     *     *
*    *    *    *    *    *    *    *    *     *     *
     *    *    *    *    *    *    *    *     *     

Next, to see how well the random number generator is doing, I write a function to compute the average value rolled. Compare this to the ideal average of 7. Also, print out a small table showing the counts of each roll made by the program, the ideal count based on the frequencies above given the total number of rolls, and the difference between these values in separate columns. This is my incomplete code so far: "Compiler visual studio 2010"

int rolling(){    //Function that returns a random value between 1 and 6
rand(unsigned(time(NULL)));
int dice = 1 + (rand() %6);
return dice;
}
int roll_dice(int num1,int num2){ //it calls 'rolling function' twice 
int result1,result2;
num1 = rolling();
num2 = rolling();
result1 = num1;
result2 = num2;
return result1,result2;
}
int main(void){
int times,i,sum,n1,n2;
int c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11;//counters for each sum
printf("Please enter how many times you want to roll the dice.\n")
scanf_s("%i",&times);

I pretend to use counters to count each sum and store the number(the count) in an array. I know i need a loop (for) and some conditional statements (if) but m main problem is to get the values from roll_dice and store them in n1 and n2 so then i can sum them up and store the sum in 'sum'.

© Stack Overflow or respective owner

Related posts about c++

Related posts about visual-studio