+ 6

I'm really so confused on this. (float num = 50/100;) (cout<< num <<endl;) output 0 instead 0.5; why?

float num = 50 / 100; cout<< num <<endl; // output 0 instead 0.5

15th Jun 2022, 7:04 PM
IbrahimCPS
IbrahimCPS - avatar
7 Respuestas
+ 9
Right hand side 50 and 100 both are int type values so int/int result int type only.. Take as fractional (float Or double type) number , atleast one of those two, then see result. hope it helps.... edit: below all 50.0/100 50/100.0 50.0/100.0 output : 0.5
15th Jun 2022, 7:10 PM
Jayakrishna 🇮🇳
+ 6
I understand it very well thank to Jayakrishna🇮🇳 A͢J i use float num = 50. / 100.; //output 0.5
15th Jun 2022, 7:34 PM
IbrahimCPS
IbrahimCPS - avatar
+ 4
IbrahimCPS You have assigned float to num not float to (50 / 100) both are integer and divide with higher integer value will give 0
15th Jun 2022, 7:30 PM
A͢J
A͢J - avatar
+ 4
Stefan Corneteanu like how? F at the end of it or with explicit conversation. show us.
16th Jun 2022, 5:22 PM
IbrahimCPS
IbrahimCPS - avatar
+ 4
Wow; thank you very much Stefan Corneteanu
16th Jun 2022, 5:27 PM
IbrahimCPS
IbrahimCPS - avatar
+ 1
Either turn one of the numbers to float by adding .0 or F at the end of it, or with explicit conversion
16th Jun 2022, 5:14 PM
Stefan Corneteanu
Stefan Corneteanu - avatar
+ 1
IbrahimCPS 50 is an int 50F or 50f is a float (float)50 is explicit type conversion of integer 50 to a float
16th Jun 2022, 5:25 PM
Stefan Corneteanu
Stefan Corneteanu - avatar