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;
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With