-1

I was just playing around with data types and landed on this dilemma. Can anyone here explain me the reason

#include<iostream>
using namespace std;

int main() {

    float a= 0.7;
    if(a < 0.7)
        cout<<"Yes";
    else
        cout<<"No";
    return 0;
}

I know it is because automatically 0.7 as a literal will be of double.

#include<iostream>
using namespace std;
int main(){

    float a= 0.8;
    if(a < 0.8)
    cout<<"Yes";
    else
    cout<<"No";
    return 0;
}
Kashif Faraz Shamsi
  • 513
  • 1
  • 7
  • 21
  • 1
    Because 0.7 cannot be represented exactly as a binary floating point number. – Ian Abbott Aug 31 '17 at 16:19
  • And what *is* your "dilemma"? What is the problem with the code you show? What is the actual and expected output? Please put all that *in the body of the question*, the title should just be a short summary of the question in the body. Please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask) if you haven't already. – Some programmer dude Aug 31 '17 at 16:20
  • https://stackoverflow.com/q/7011184/995714 https://stackoverflow.com/q/6883306/995714 https://stackoverflow.com/q/16698198/995714 – phuclv Aug 31 '17 at 16:22
  • Of course, one question may be that it assigned 0.7 to a variable and then compared the variable to 0.7, so shouldn't they be equal? And the answer is "no", because the 0.7 is converted from `double` to `float` by the assignment to the variable, losing some precision in the process, and converted back from `float` to `double` for the comparison, but the values are no longer equal. – Ian Abbott Aug 31 '17 at 16:23
  • 1
    So the question might not be an exact duplicate, due to the niggle of comparing the variable to the value that was just assigned to it. – Ian Abbott Aug 31 '17 at 16:25
  • `float a = 0.7` == 0.699999988, but `auto b = 0.7` == 0.69999999999999996 because it is treated as double. (The second duplicate reference explains this) – wally Aug 31 '17 at 16:31
  • 3
    Try changing the test to `if(a == 0.7f)` and it should print "Yes". – Ian Abbott Aug 31 '17 at 16:31
  • Seriously? This *exact* same question was already asked. https://stackoverflow.com/questions/45932836/c-data-types-concept#comment78823945_45932836 – StoryTeller - Unslander Monica Aug 31 '17 at 18:03

1 Answers1

1

0.7 has no exact representation as float. The approximate float is a bit less than the double representation of 0.7 (which is the default interpretation when use as a constant in the if statement) .

For more details on that, see the question linked for duplicate or the countless variations in the comments.

Pac0
  • 21,465
  • 8
  • 65
  • 74