+ 1

Why it shows "bad" in answer?

include<stdio.h> int main() { float x = 2.8; if(x==2.8) { printf("Good") ; }else{ printf("Bad") ; } return 0; }

17th Sep 2021, 2:32 AM
Charchit Khandelwal
Charchit Khandelwal - avatar
2 ответов
+ 5
A floating point literal such as 2.8 in C/C++ by default is defined as `double` type. The precision difference between `float` and `double` type makes it tricky when performing comparison between variables of the two types. To overcome the comparison issue, you can explicitly tell the compiler to define the literal 2.8 as `float` by appending 'f' for the literal e.g. 2.8f. This way both <x> and literal 2.8 will both be of a `float` type if( x == 2.8f ) // <- notice the 'f' // more code follows ...
17th Sep 2021, 2:48 AM
Ipang
+ 1
Try this #include <stdio.h> int main() { float x = 2.8; float y = 2.8 ; if(x==y) { printf("hell9"); }else{ printf("hello"); } return 0; }
17th Sep 2021, 2:40 AM
Pariket Thakur
Pariket Thakur - avatar