Change Due – Solution

I confess, the solution to this month’s Exercise was frustrating. Several times, I thought to abandon the premise and focus on the main problem, which is how to create a random price, such as $5.32, without that floating-point value really being 5.3187321.

Normally, you can code prices using float variables straight-up. Financial institutions calculate fractions of cents when they work out interest and such. So a real number works fine, and the %.2f placeholder in a printf() statement shows the proper result. For a rounding exercise, however, the values must be limited to only two digits of precision — cents.

My first thought was to use the modulus operator (%) to hack off a real number, but the modulus operator works only with int values. Instead, I crafted floating point values using two random number calls, one for the dollars and the other for the cents:

    /* calculate item's random cost */
        /* pennies */
    item_cents = rand()%100;
        /* dollar */
    item_dollars = rand()%MAX_COST;
        /* build original price */
    original_price = (float)item_dollars + (float)item_cents/100.0;

Integer variable item_cents contains a random number between 0 and 99. Integer variable item_dollars contains a value from 0 to MAX_COST, which in my code is defined as 10. The original_price variable is a float. Typecasting recajiggers item_dollars and item_cents to a float value, item_cents. That value is divided by 100, which results in a real number with only two decimal places guaranteed.

After the item’s original price is obtained, the code determines the rounded price using the original int value for cents:

    /* round off to the nearest nickel */
    diff = item_cents % 5;
    round_price = original_price - (float)diff/100.0;

Above, I use the original int variable item_cents with the modulus operator to round down to the next nickel. Then the value round_price is calculated by subtracting the rounded-down value (the pennies) from the original price.

The rest of the code displays the two values and calculates a running total for each. You can view the entire code here. And, yes, as you expect, you save more when each price is rounded down, but only a small amount.

Another way to calculate the solution is to use the fmod() function. fmod() is the floating-point remainder function, which requires two double arguments:

fmod(a,b)

The fmod() function, defined in math.h, returns the remainder of a/b. So if a is some random price and b is 0.05, the result is similar to a % 0.05. You could truncate any floating point value to the second decimal position by using this equation:

round_price = fmod(original_price,0.01);

If you used fmod() in your solution instead of the cobbled-together-integers solution I attempted, then I’ll give you extra For Dummies bonus points.

Leave a Reply