Does anyone know why it prints a? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Does anyone know why it prints a?

#include <stdio.h> int main() { float a=0.7; if(0.7>a){ printf("a"); } else{ printf("b"); } return 0; }

12th Nov 2023, 6:26 PM
HoaiNam
HoaiNam - avatar
7 Answers
+ 7
Add this to the code for a answer: if(0.7>a){ printf("a\n"); printf("a= %.9f", a); }
12th Nov 2023, 7:06 PM
JaScript
JaScript - avatar
+ 2
It happens because there is a chance that a variable stores slightly less value of 0.7 due to the limitations of float values
12th Nov 2023, 7:11 PM
ADITYA MISHRA
ADITYA MISHRA - avatar
+ 1
Ok, I see, thank you
12th Nov 2023, 7:27 PM
HoaiNam
HoaiNam - avatar
+ 1
float variable value is 0.7 I.e a=0.7. 0.7 is double constant value and double constant value is greater than float variable value that's why it satisfied the if condition and print a as an output. For instance: int main() { float a=0.7 ; double b=0.7; printf("%.10f %.10lf",a,b); } Output : value of a = 0.699999.... value of b= 0.7000000... So,double variable value(0.7000...) is greater than float variable value(0.6999...). I hope I answered your question.
15th Nov 2023, 6:39 AM
Ayush Raj
0
You are printing a [printf("a")] not the value of a to print the value of a it should be print("%f" a)
13th Nov 2023, 10:27 AM
Neha
Neha - avatar
0
You can double instead of float because, the compiler treats 0.7 as a double literal, not a float.
14th Nov 2023, 3:23 PM
Imara Mohideen
Imara Mohideen - avatar
0
Instead of 0.7>a you can do (float)0.7>a. This is because double is bigger than float. float a=0.7; if((float)0.7>a){ printf("a"); } else{ printf("b"); }
14th Nov 2023, 4:14 PM
Werg Serium
Werg Serium - avatar