Computer Science, asked by virendra12575, 8 months ago

What is the output of the following code? double d 4.669; printf("My number is %.2f.", d);​

Answers

Answered by vipinraj16
0

Answer : I see several answers that suggest the number shown will be either 4.66 or 4.67 as there’s some confusion on how C should . Modern compilers will follow the and will round to the nearest number or to the nearest even number if it’s a tie. So 4.669 gets rounded to 4.67 while 4.665 gets rounded to 4.66… (Because nearest even!)

But the C standard does not determine how %.2f should be rounded! So the rounding rule used depends on the compiler used. Most compilers will interpret it as “Round to two decimals” but some will implement it as “Take the first two decimals”.

If I’m not mistaken, the C++ language does supply the right method to use with printf, which is the IEEE standard.

It’s a bit more complex as there’s yet another rounding option, where tie-breaks are rounded away from 0. Or when rounding is always away from 0. (Or towards zero!) There’s a whole lot of science going behind it and the most common errors occur because of rounding errors.

Similar questions