Search code examples
c++runtime-erroroperators

Why does the lesser than equal to operator show unexpected behavior for two ```double``` values in C++?


This is the link for the problem that I was trying to solve: https://www.codechef.com/problems/HS08TEST

It's a pretty straightforward problem with just three scenarios so I was sure that the code would run. However, I got the wrong answer message (the website doesn't show what has gone wrong). My code is as follows :

#include<bits/stdc++.h>

using namespace std;

double w, b;

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> w >> b;
    cout << fixed;
    if(fmod(w, 5) == 0.0 && w <= b)
        cout << setprecision(2) << (b - w) << "\n";
    else
        cout << setprecision(2) << b << "\n";
}

The solutions which were marked as correct by the site did a rather odd thing : (w+0.5)<=b Their claims (Without explanation) were that if we don't put the 0.5 part in, <= returns a -ve result. Can someone explain what is the exact issue here?

EDIT

Due to floating point precision issues, I was advised to add 0.5 so that the computer can perform the comparison. Now according to maths a<b is the same as a+c<b+c (Inequalities). I used that principle to write (w+0.5)<=(b+0.5). However,even this gives a Wrong Answer Message ! The code used :

#include<bits/stdc++.h>

using namespace std;

double w, b;

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cin >> w >> b;
    cout << fixed;
    if(fmod(w, 5) == 0.0 && (w+0.5) <= (b+0.5))
        cout << setprecision(2) << (b - w) << "\n";
    else
        cout << setprecision(2) << b << "\n";
}

Solution

  • In the problem, there is a condition like, " For each successful withdrawal the bank charges 0.50 $US". If you have 5$ in your account you cannot withdraw 5$. You can withdraw 5$ - 0.50$ = 4.50$ as you have to keep 0.05$ for transaction fee. It needs to be assured before withdraw that you have a transaction fee left in your account. So we have to check withdraw + 0.5 <= balance. Here, 0.5$ for the transaction fee. w <= b or w + 0.5 <= b + 0.5 will give the wrong answer because when you have a 5$ balance and you are going to withdraw 5$ it will be accepted according to the condition. Without the transaction fee, one cannot withdraw. Therefore, we have to add 0.5 with the withdraw when checking. Another way we can do it is w <= b - 0.5, excluding transaction fees from the account balance.