double total,grandtotal;
double amount, change=0;
total=day* price* noRoom;
grandtotal=total*1.16;
cout<<"\t\tPlease enter your amount:RM";
cin>>amount;
while (amount < grandtotal)
{
cout << "\t\tPlease enter a valid amount:RM";
cin >> amount;
}
change=amount-grandtotal;
if (amount > grandtotal)
{
cout<<"\t\tYour change is: "<<change <<endl;
cout<<"\t\tThank You, Have a nice day! \n";
cout<<"\t\t Please come again \n";
}
else if( amount == grandtotal) //why this statement can't run if my amount is also equal to the grandtotal???
{
cout<<"\t\tThank You, Have a nice day! \n";
cout<<"\t \tPlease come again \n";
}

- 12,860
- 3
- 34
- 61

- 31
-
3Some reading: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html and http://stackoverflow.com/help/how-to-ask – deviantfan Nov 26 '14 at 13:30
-
His problem is described as comment in his else if – deW1 Nov 26 '14 at 13:31
-
1Put the question outside the code block and people might retract their downvotes. – daramarak Nov 26 '14 at 13:31
-
1@Elmi Being a beginner in programming and in conversation is different. If someone expects us to be mindreaders (or looking through some code to find english sentences) to understand something... – deviantfan Nov 26 '14 at 13:31
2 Answers
Your else if
might be executed but most likely it won't happen, because double
values precision is relatively high so there will be difference.
If you set the precision smaller for example that should work.
eg 2.11 == 2.11 rather than 2.15151523 == 2.15151524
This question might help you doing so.
-
-
You can do that but that will only affect the output. I've put in a link in my answer where you can read about a way to achieve the precision you want. – deW1 Nov 26 '14 at 14:08
My observation is that you are using floating point values for financial transactions. This is not a good idea. The representation of floating point numbers can be approximate for certain floating point values. It would be much better to use (long) integers to represent the pence/cents, and then represent the larger denomination in the output function.
That way your test will work.
In some contexts you may want to compare floats then use a very small constant floating point value perhaps called epsilon and have the test.
if (fabs(amount - grandtotal) < epsilon)
{
cout<<"\t\tThank You, Have a nice day! \n";
cout<<"\t \tPlease come again \n";
}

- 196
- 1
- 10