5

Possible Duplicate:
strange output in comparision of float with float literal
Why comparing double and float leads to unexpected result?

In following code I was expecting answer to be "Not equal", because by default the 3.5 should be double in C++, but the result was "equal".

What is difference in declaring float a=3.5f and float a=3.5?

#include<iostream>
using namespace std;

int main()
{
    float a=3.5;
    if(a==3.5)  
        cout<<"equal"<<endl;
    else
        cout<<"Not equal"<<endl;
    return 0;
}
Community
  • 1
  • 1
Abhishek Gupta
  • 981
  • 4
  • 10
  • 20

2 Answers2

14

No.

The type of3.5 is double whereas the type of 3.5f is float. So they are not guaranteed to be equal in values.

#include<iostream>

void f(double) { std::cout << "it is double" << std::endl; }
void f(float)  { std::cout << "it is float" << std::endl; }

int main()
{
   f(3.5);
   f(3.5f);
}

Output:

it is double
it is float
Nawaz
  • 327,095
  • 105
  • 629
  • 812
  • 2
    `3.5 == 3.5f` *is* guaranteed by IEEE754, which most "normal" systems use these days. – fredoverflow Apr 28 '12 at 08:10
  • But 10.0f/3.0f is not guaranteed to be equal to 10.0/3.0. He happened to pick an exact number. – David Hammen Apr 28 '12 at 08:21
  • @FredOverflow: Yes, *"3.5 == 3.5f is guaranteed by IEEE754"*, but it is not guaranteed by C++, as an implementation can choose *any* floating-point format. – Nawaz Apr 28 '12 at 11:43
2

Float are not an exact number. Comparing them with == is never an good idea. Here is why: What Every Computer Scientist Should Know About Floating-Point Arithmetic

RvdK
  • 18,577
  • 3
  • 56
  • 100
  • 8
    Floats _do_ represent exact numbers; however, there are many numbers which cannot be represented by any float. – Mankarse Apr 28 '12 at 07:48