// Dice Statistics Program (looping demo)

// Given the size of two dice and a target number
// Find out the chance of rolling the target number
// and report it as a percentage.

// This is a demo of looping with a little bit of
// discussion about division of integers. 

// Marc Chee (cs1511@cse.unsw.edu.au), June 2020

#include <stdio.h>

int main(void) {
    // Take user input on the size of the two dice
    int dieOneSize;
    int dieTwoSize;
    int targetValue;
    printf("Please enter the size of the first die: ");
    scanf("%d", &dieOneSize);
    printf("Please enter the size of the second die: ");
    scanf("%d", &dieTwoSize);
    printf("Please enter the target value: ");
    scanf("%d", &targetValue);
    
    int numCombos = 0;
    int numMatches = 0;
    
    // loop through all the possible values of dieOne
    int dieOne = 1;
    // the command to stop a program (especially in the case
    // of an infinite loop) is Ctrl-C
    while (dieOne <= dieOneSize) { // we have seen dieOne - 1 values        
        int dieTwo = 1;
        while (dieTwo <= dieTwoSize) { // we have seen dieTwo - 1 values
            int total = dieOne + dieTwo;
            numCombos++;
            // print out the dice combo if the total matches the target value
            if (total == targetValue) {
                numMatches++;
                printf(
                    "dieOne: %d, dieTwo: %d. Total: %d\n", 
                    dieOne, dieTwo, total
                );
            }
            dieTwo++;
        }        
        dieOne++; // is the same as dieOne = dieOne + 1;
    }
    
    printf(
        "Out of %d combinations, %d matched the target value.\n", 
        numCombos, numMatches
    );
    
    printf("%d divided by %d = %d\n", numMatches, numCombos, numMatches/numCombos);
    
    printf(
        "%lf%% chance of rolling a %d.\n", 
        (numMatches/(numCombos * 1.0)) * 100, targetValue
    );
}








Resource created Sunday 14 June 2020, 02:12:29 PM.

file: diceStats.c


Back to top

COMP1511 20T2 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G