+ 1
When the output is the same why the compiler prints not eq? Because of data type?
#include <iostream> int main() {float a=2.2; double b=2.2; if(a==b) {std::cout<<"eq";} else{std::cout<<"Not eq"<<"\n";} std::cout<<a<< " "<<b; }
4 Respostas
+ 5
This is because of difference in the number of bits available for float and double.
Suppose there’s a number 1.1- it’s binary representation is- 1.0001100110011……
Now float can take only some digits after the decimal place whereas double can take larger number of digits after the decimal place. Thus the value of 1.1 in float is different from the value of 1.1 stored in double.
If we take the example 1.5; it’s binary representation is- 1.1 and it is same for both float and double because it needs only 1 digit after the decimal point.
We can understand better with the following example -
#include<stdio.h>
void main ()
{
float a=1.1;
float b=1.125;
if (a==1.1)
printf("a is Equal");
else
printf("a is Not Equal");
if (b==1.125)
printf("\n b is Equal");
else
printf("\n b is Not Equal");
}
It's output is-
a is Not Equal
b is Equal
+ 2
Nariman Tajari
Yep
data type is important to a computer
+ 2
Kashyap Kumar nixe job.
After your answer i understand the reason completely.
+ 1
By default floating value treat as double type value if u writing like this
1.111233 then its not float its double value in your case you assigned 1.1 which double value to float variable a .
Think about it how can u store big data in small container
So your float variable a unable to hold double value that's why it will loose some precision .
Conversion from (am talking in c cpp in java its little different)
short data to int valid ,
Int to float valid
Float to double valid
here we going lower to higher
But
Double to float is not valid if u will try this then it will lose some bits if u wan to see difference then u can print
Values till 20 digits after decimal
like
float a=1.1
print (%.20, a)
print (%.20 ,1.1)
Solutions : in this case u need to do type casting in c++ you can use static_cast<>