0

I wrote a program and have problem with results. When I'm enter some numbers, for example 43.01, conditional operator ignores that statement is true and gives me a wrong output ( 0 cents ), where is the problem?

int main()
{
    double money_amount;
    cout << "Enter money amount. For example: 3.59\n";
    cin >> money_amount;
    int dollar_amount = money_amount;
    double cent_amount = money_amount - dollar_amount;
    cout << cent_amount << "\n"; // to make sure that there is 0.01
    dollar_amount == 1 ? cout << "You have 1 dollar\n" : cout << "You have " << dollar_amount << " dollars\n";
    cent_amount == 0.01 ? cout << "You have 1 cent\n" : cout << "You have " << floor(cent_amount*100) << " cents\n"; // here is the problem
}
  • I have a problem with cents amount. I make dollar_amount as int consciously, it automaticly rounds off number, instead of using floor. – John Reqemail Aug 25 '17 at 18:14
  • You cant use the ?: operator like this. Rewrite using "if then else", it is easier to get it right and it will be much more readable – Stefan Aug 25 '17 at 18:14
  • 1
    @JohnReqemail Work in pennies (integer), not double. – PaulMcKenzie Aug 25 '17 at 18:14
  • Direct compare of a double/float to 0.01 is not going to work - hence the duplicate marker. This is why the suggestion of using integer pennies was made. Work with pennies and div/mod 100 to get the dollar/cent amounts. – Michael Dorgan Aug 25 '17 at 18:16
  • @PaulMcKenzie So the problem is in the feautures of floating point math? – John Reqemail Aug 25 '17 at 18:17
  • @JohnReqemail -- The computer works in binary. What is the binary equivalent of the decimal fraction `0.01`? It is a non-repeating, non-terminating binary floating point number. Thus there is no exact representation of `0.01` in binary, thus the round-off errors you will get. That, in a very small nutshell, is the issue. You can google for more information on things like this. – PaulMcKenzie Aug 25 '17 at 18:20
  • Thanks a lot, espicially to @PaulMcKenzie – John Reqemail Aug 25 '17 at 18:23
  • @PaulMcKenzie, tell me please why "cout << cent_amount" give 0.01 in output rather than 0.010000000123? – John Reqemail Aug 25 '17 at 18:32
  • @JohnReqemail -- That is because it is formatted in a certain way. An output routine can do anything with the number. When you use that number in calculations, it isn't `0.01`. – PaulMcKenzie Aug 25 '17 at 18:44

0 Answers0