With the following simple C++ exercise
#include <iostream>
using namespace std;
int main()
{
int euro, cents_v1, cents_v2, do_again;
double price;
do_again = 1;
while(do_again != 0){
cout<<"Insert price in Euro with cents"<<endl;
cin>>price;
euro = price;
cents_v1 = price*100 - euro*100;
cents_v2 = (price - euro) * 100;
cout<<"Total: "<<euro<<" euro and "<<cents_v1<<" cents"<< endl;
cout<<"Total: "<<euro<<" euro and "<<cents_v2<<" cents"<< endl;
cout <<"\nDo it again? 1: yes, 0: no."<<endl;
cin>>do_again;
}
return 0;
}
You can obtain two different answers, if the input is, for example 31.13:
Insert price in Euro with cents
31.13
Total: 31 euro and 13 cents
Total: 31 euro and 12 cents
Do it again? 1: yes, 0: no.
How to deal with this problem? Is there a rule in programming to avoid or to control this issue in more complicated situations?