Wednesday, November 27, 2019
Simulate a Dice Roll With C Code
Simulate a Dice Roll With C Code This application uses the srand() function to seed the random number generator. The function Random(n) returns an integer in the range of 1 to n. The int array totals holds the total counts for the scores 3 to 18. It then loops 10 million times. This number is defined as a const but if your compiler doesnt support const, uncomment the #define instead. Each dice, d1, d2 and d3 holds the Random() generated dice roll die roll and the element for the combined dice score (in the range 3-18) is incremented. The last part prints out the totals to see that it generates throws in accordance with the probabilities. A 6 sided dice has an average score of 3.5, so three dice should average about 10.5. The totals for 10 and 11 are roughly the same and occur about 12.5% of the time. Here is the output of a typical run. It takes no more than a second. Rolling Ten Million Dice 3 461304 1386085 2772786 4626077 6953818 9720209 115834710 125367111 124926712 115648013 97200514 69287415 46245216 27757517 13914218 46163 // dicerolls.c :#include time.h /* Needed just for srand seed */#include stdlib.h#include stdio.hconst tenmillion 1000000L;/* #define tenmillion 10000000L */void Randomize() {srand( (unsigned)time( NULL ) ) ;}int Random(int Max) {return ( rand() % Max) 1;}int main(int argc, char* argv[]){int i;int totals[19];printf(Rolling Ten Million Dice\n) ;Randomize() ;for (i3;i18;i)totals[ i ]0;for (i0;i tenmillion;i){int d1Random(6) ;int d2Random(6) ;int d3Random(6) ;int totald1d2d3;totals[ total ];}for (i3;i18;i){printf(%i %i\n\r,i,totals[ i ]) ;}return 0;}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.