// DiceAndProbability.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "math.h" #include "time.h" int roll_frequency[121]; int die[21]; void roll_many_dice(int sum, int dice_count); int _tmain(int argc, _TCHAR* argv[]) { int number_of_dice; int roll, sum; time_t t1; time_t t2; struct tm *tblock1; struct tm *tblock2; int start_hour, end_hour; int start_min, end_min; int start_sec, end_sec; // Get the number of dice user wishes to roll printf("Enter the number of dice you wish to roll: "); number_of_dice = 0; scanf("%d", &number_of_dice); while((number_of_dice <= 0) && (number_of_dice > 20)){ printf("\a\a\a Error: Number of dice must be within 1 through 20. Try again: "); scanf("%d", &number_of_dice); } //Get the time the program starts t1 = time(NULL); tblock1 = localtime(&t1); start_hour = tblock1->tm_hour; start_min = tblock1->tm_min; start_sec = tblock1->tm_sec; //Call the recursive function roll_many_dice(0, number_of_dice); //List the results: frequency and probability of each roll for(roll=1; roll<=6*number_of_dice; roll++) printf("%2d Dice: roll %3d occurs with frequency: %10d, probability %7.12f\n", number_of_dice, roll,roll_frequency[roll], roll_frequency[roll]/pow(6.0,number_of_dice)); //Get the ending time of the program t2 = time(NULL); tblock2 = localtime(&t2); end_hour = tblock2->tm_hour; end_min = tblock2->tm_min; end_sec = tblock2->tm_sec; //Print the start and end time of the program for comparison printf("Program Start (hr:min:sec): %2d:%2d:%2d\n", start_hour, start_min, start_sec); printf("Program End (hr:min:sec): %2d:%2d:%2d\n", end_hour, end_min, end_sec); //Done! Finally! return 0; } void roll_many_dice(int sum, int dice_count) { int face; // 1, 2, 3, 4, 5, or 6 if(dice_count == 1) //...we're on the last die! almost done! for(face=1; face<=6; face++) roll_frequency[sum+face]++; //Add the last die to the total roll else for(face=1; face<=6; face++)//...This isn't the last die! roll_many_dice(sum+face, dice_count-1); //Recursively call the dice roll subroutine for the remaining n-1 dice return; }