+ 1

how integer and double(float) are equal ?

https://code.sololearn.com/cuJ18fu3my0Z/?ref=app

8th Nov 2020, 6:18 AM
Shrinivas Gadade
Shrinivas Gadade - avatar
11 Respostas
+ 3
In the code it is only checking the values of the variables, its not checking what type it is. Both of the variables values are same, it is 2. To check type u have to use typeof function if( typeof(varOne) == typeof(varTwo) ) { printf("both are same type"); }
8th Nov 2020, 6:26 AM
Steve Sajeev
Steve Sajeev - avatar
+ 2
For any integer of a reasonable size you can compare it exactly to a float. Once your integer is greater than 2^22 or 2^23, floats can't represent it accurately, esp. if it is odd (if it is even or a multiple of 2^N, the exponent part of the float can compensate for it. If you compare a double to int, it has a 53 bit mantissa so an integer less than 53 bits will be equal to its double counterpart. Only when you have larger integers your double <> int comparisons will fail. (to get 64 but it's you may use int, long or long long, fermenting on your compiler, memory model and cpu architecture)
8th Nov 2020, 4:00 PM
Udi Finkelstein
Udi Finkelstein - avatar
+ 1
Because the double: 2.000000 is equal to the integer: 2. They have the same value
8th Nov 2020, 6:24 AM
Slick
Slick - avatar
+ 1
You can try same code but with 0.25 value and you will see than a and b will be same value after comparison because either double and float can represent 0.25 value without losing precision (0.25 is a power of 2 or 2 ^ -2)
8th Nov 2020, 7:26 AM
KrOW
KrOW - avatar
+ 1
thanks
8th Nov 2020, 7:40 AM
Shrinivas Gadade
Shrinivas Gadade - avatar
8th Nov 2020, 7:41 AM
Avinesh
Avinesh - avatar
0
Slick , Steve Sajeev ok, if this is case then : #include <stdio.h> int main() { float a = 0.2f; double b = 0.2; if(a == b) { printf("hi"); } else { printf("bye"); } return 0; } output : bye why in the above code it is showing out as "bye" , it should show output as "hi" , because here also values are same ?
8th Nov 2020, 7:10 AM
Shrinivas Gadade
Shrinivas Gadade - avatar
0
them are not same representation in memory but compiler add some instruction to convert implicitally the int to double for comparison purpose that make them comparable to memory level
8th Nov 2020, 7:18 AM
KrOW
KrOW - avatar
0
KrOW and about float and double comparison ?
8th Nov 2020, 7:21 AM
Shrinivas Gadade
Shrinivas Gadade - avatar
0
The problem in your second example is precision... float is less precise than double and after conversion to double 'a' will not has same value than 'b' (in this case)
8th Nov 2020, 7:22 AM
KrOW
KrOW - avatar
0
Shrinivas Gadade when you compare an integer with a float, the program creates a temporary float copy of the integer and than execute the comparison. Read this page for more info: https://overiq.com/c-programming-101/implicit-type-conversion-in-c/
8th Nov 2020, 10:51 AM
Davide
Davide - avatar