/* Dice Checker Lecture Demo Continued
Marc Chee (cs1511@cse.unsw.edu.au), June 2020
This small example will ask the user to input the
result of two dice rolls.
It will then check the sum of them against its
secret number.
It will report back:
a success (higher or equal)
a failure (lower)
In this extended example, we worked through what
the program could do if it received input values
outside the range it expected. We looked at different
options, ranging from exiting the program to
correcting input in different ways.
*/
#include <stdio.h>
#define SECRET_TARGET 7
#define MIN_VALUE 1
#define MAX_VALUE 6
int main(void) {
// read in and store the value of the first die
int dieOne;
printf("Please input the value of the first die: ");
scanf("%d", &dieOne);
// This error checking is an example of us reading incorrect
// input and correcting it.
if (dieOne >= MIN_VALUE && dieOne <= MAX_VALUE) {
// valid roll
} else {
// invalid roll
printf(
"Die One, %d, was outside the range %d-%d.\n",
dieOne, MIN_VALUE, MAX_VALUE
);
/* correct the invalid input using clamping
if (dieOne < MIN_VALUE) {
dieOne = MIN_VALUE;
} else if (dieOne > MAX_VALUE) {
dieOne = MAX_VALUE;
} */
// correct invalid input using modulus
dieOne = dieOne % MAX_VALUE;
printf("dieOne after modulus is: %d\n", dieOne);
if (dieOne == 0) {
dieOne = MAX_VALUE;
printf("corrected value from 0 to %d\n", dieOne);
} else if (dieOne < 0) {
// Two options for dealing with negative mod outcomes here
//dieOne = dieOne + MAX_VALUE;
dieOne = dieOne * -1;
printf("corrected negative value to %d\n", dieOne);
}
}
// read in and store the value of the second die
int dieTwo;
printf("Please input the value of the second die: ");
scanf("%d", &dieTwo);
// This error checking is an example of us rejecting incorrect
// input and just exiting the program.
if (dieTwo >= MIN_VALUE && dieTwo <= MAX_VALUE) {
// valid roll
} else {
// invalid roll
printf("Die Two, %d, was incorrect. Program will exit now.\n", dieTwo);
return 1;
}
int total = dieOne + dieTwo;
printf("Total of the dice roll is: %d\n", total);
// Check the total against the secret number
if (total >= SECRET_TARGET) { // Success
printf("Success!\n");
} else { // Failure
printf("Failure!\n");
}
return 0;
}
Resource created Tuesday 09 June 2020, 11:54:43 AM.
file: diceChecker.c