+ 2

Where is the 5 goes?

printf("%08.3f", 17.3456); /* output: 0017.346*/ Why the output is 0017.346 and not 0017.345? And when i change it like this.. printf("%08.3f", 17.345); /* output: 0017.345*/ The output now is what i'm expected...

9th Dec 2020, 10:50 AM
ZΛRTHΛИ
ZΛRTHΛИ - avatar
3 Respostas
+ 2
Because the next decimal is greater than 5 e.g. 4.1234 = 4.123 4.1267 = 4.127 And same with that case, you round the number into 3 decimal places --> 17.3456 --> 17.345(6) <-(6 is greater than or equal to 5) --> 17.34(5+1) <-(if next decimal is greater than 5 add 1 to the decimal to its left. == 17.346
9th Dec 2020, 10:56 AM
noteve
noteve - avatar
+ 5
Adding to what had been pointed out correctly early on, the number 17.3456 had 4 decimal points, but format specifier "%08.3f" allows only 3 decimal points, meaning, a rounding was in order. Notice that by adding decimal point (to 4 points) in format speciifier we can get output as expected. printf("%08.4f\n", 17.3456); // 08.4f output 017.3456 // width 8 characters, pad with '0' // where necessary, 4 decimal // point allowed, type float printf("%08.3f\n", 17.3456); // 08.3f output: 0017.346 // width 8 characters, pad with '0' // where necessary, 3 decimal // point allowed, type float P.S. The decimal separator '.' is also counted in width specifier.
9th Dec 2020, 11:12 AM
Ipang
+ 2
Because of the ".3f" it rounding your number.
9th Dec 2020, 10:58 AM
rodwynnejones
rodwynnejones - avatar