Write a C++ program that simulates the throw of a dice. The program allows the u
ID: 3545841 • Letter: W
Question
Write a C++ program that simulates the throw of a dice. The program allows the user to enter the number of throws he/she would like to do. The program then, will calculate the statistics of the number of faces appears in these throws. The program should satisfies the following:
- Do NOT use arrays, only functions.
- You need to implement all of your program activities in separate functions. Then test your function from within the main function. You should not do any calculation or task in the main function ( apart from calling the functions ).
- Make sure that the program will not allow the user to enter inappropriate values of the number of throws (Such as 0,-1,-2.........)
- In case inappropriate number entered, the program should prompt the user to re-enter the number of throws again until is entered correctly.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int rollDie( void ) {
/* the following properly maps rand() as uniform deviates. */
/* the modulus operator, %, does not properly map rand(). */
return 1 + (int) floor( 6.0 * rand() / (1.0 + RAND_MAX) );
}
int rollDice( void ) {
int die1, die2;
char b[100];
printf( "Roll (enter 0 to stop)? " );
if ( fgets( b, sizeof(b), stdin ) == NULL || b[0] == '0' ) return 0;
die1= rollDie( );
die2= rollDie( );
printf( "Player rolled %d + %d = %d ", die1, die2, die1+die2 );
return die1+die2;
}
int main( void ) {
int bankRoll, roll;
srand( time( NULL ) );
for ( bankRoll= 100; bankRoll >= 0 && (roll= rollDice()) != 0 ; ) {
switch ( roll ) {
case 7:
bankRoll += 50;
printf( "You win." );
break;
default:
bankRoll -= 10;
printf( "You lose." );
break;
}
printf( " Current bankroll is %d ", bankRoll );
}
if ( bankRoll < 0 )
printf( "You broke your bankroll! You owe $%d. ", -bankRoll );
else if ( bankRoll < 100 )
printf( "You lost $%d. ", 100 - bankRoll );
else if ( bankRoll == 100 )
printf( "You broke even. ");
else
printf( "You made $%d. ", bankRoll - 100 );
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.