Why my C++ program outputs (0.2 / 0.1) = 1 instead of 2?

  arithmetic-expressions, c++, ieee-754, math

The program is meant to convert a USD($) quantity inputted by the user (from $0 to $10 max) and output it in quantities of quarters, dimes, nickles, and pennies.


#include <iostream>

const double QUARTER {0.25};
const double DIME {0.10};
const double NICKLE {0.05};
const double PENNY {0.01};

void dollarToCoin(double cash, unsigned short& quarters, unsigned short& dimes, unsigned short& nickles, unsigned short& pennies){
    
    double cashRemainder = cash;
    quarters = cashRemainder / QUARTER;
    cashRemainder -= QUARTER * quarters;
    dimes = cashRemainder / DIME;
    cashRemainder -= DIME * dimes;
    nickles = cashRemainder / NICKLE;
    cashRemainder -= NICKLE * nickles;
    pennies = cashRemainder / PENNY;
    cashRemainder -= PENNY * pennies;
    std::cout << "Remaining cash: " << cashRemainder << 'n';

}

int main(){
    
    double cash{0};
    unsigned short quarters{0};
    unsigned short dimes{0};
    unsigned short nickles{0};
    unsigned short pennies{0};
    
    std::cout << "Input your cash ($0 - $10 max): ";
    std::cin >> cash;
    dollarToCoin(cash, quarters, dimes, nickles, pennies);
    
    std::cout << "Total quarters: " << quarters <<
    'n' << "Total dimes: " << dimes <<
    'n' << "Total nickles: " << nickles << 
    'n' << "Total pennies: " << pennies << 'n';
    

    return 0;
}

The offending line is nickles = cashRemainder / NICKLE; in the dollarToCoin() function. here is the pseudocode:

  1. Starting the program, I input 1.2 as an example
  2. In the dollarToCoin() we copy the cash (1.2 dollars) into the cashRemainder
  3. We calculate quarters by dividing cashRemainder (1.2) / QUARTER (0.25) = 4.8 we save only the integer and lose the .8 (now we have 4 quarters = $1.00)
  4. We substract those 4 quarters to the cashRemainder (1.2) giving out 0.2
  5. This is my confusion part: we calculate total of times dimes = cashRemainder(0.2) / DIME (0.1) if I debug this part, it output 1 instead of 2.

If I, however, replace dimes = cashRemaindder / DIME by using –> dimes = 0.2 / DIME this actually outputs 2.

At the end of the program it should convert the input (1.2) into:

Quarters: 4, Dimes: 2, Nickles: 0, Pennies: 0

I still haven’t optimized the code nor used any libraries (by which I know there are easier ways) I’m just confused as why this happening.

Source: Windows Questions C++

LEAVE A COMMENT