0

As in the description. I'm wondering why using floats in my program works fine. But when I change them to doubles there is lack of 0.1$...

The code below is working great using floats. When I change them to doubles, the result changes.

// Example program
#include <iostream>

using namespace std;
int main()
{
    float money_rest,how_much_i_paid,real_cost_of_product;
    how_much_i_paid = 8;
    real_cost_of_product = 6.2;

    if (how_much_i_paid >= real_cost_of_product)
    {
        money_rest = how_much_i_paid - real_cost_of_product;
    }
    cout<<"I have to get back: "<<money_rest<<endl; // 1.8

    float nominals [7] = {10,5,2,1,0.5,0.2,0.1};
    int  how_much_nominals_ill_get_back = 0;
    int i = 0;

    while (i<7 && money_rest!= 0)
        {
            if (money_rest >= nominals[i])
            {

                how_much_nominals_ill_get_back = money_rest / nominals[i];
                cout << nominals[i] << " $$   x " << how_much_nominals_ill_get_back << endl;
                money_rest -= nominals[i] * how_much_nominals_ill_get_back;
            }
            i++;
        }
}

Anders
  • 2,270
  • 11
  • 19
LuQ232
  • 25
  • 1
  • 6
  • 6
    I would change that condition to `money_rest > 0.0` because otherwise you're going to run into floating point tolerance problems comparing to *exactly* 0.0 – Cory Kramer Jun 02 '20 at 18:20
  • 3
    Floating point can't represent most real numbers – expect problems if you don't use integers exclusively. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). – molbdnilo Jun 02 '20 at 18:21
  • Thanks! Now i know everything – LuQ232 Jun 02 '20 at 18:29
  • 5
    If you want to represent money values, either use integer, or use a type (probably third-party) that represents money. Don't use floating point or double. – PaulMcKenzie Jun 02 '20 at 18:34
  • 1
    You float version mixes float and double BTW, `6.2` is `double`. `6.2f` is `float`. – Jarod42 Jun 02 '20 at 18:49
  • Just in case you haven't taken it to heart, LuQ, molbdnilo's and PaulMcKenzie's advice above is very important. Represent your money as an integral number of cents (or whatever the smallest denomination you're representing is), $100 would be stored as 10,000; for example. Only convert to the display format when you receive input or display output. – JohnFilleau Jun 02 '20 at 18:54
  • The main reason why you want to use a different type than float or double to represent money is that -- you're calculating *monetary* values. If you're off by one penny, one yen, a rupee, etc. and then you multiply that value into the hundreds, thousands, or even millions, that is a *huge* mistake. Financial companies can be sued for showing values that are off, even by a few pennies, to customers and clients. – PaulMcKenzie Jun 02 '20 at 19:50

0 Answers0