#include<stdio.h>
void main()
{
float f = 2.5367;
printf("%3.3f",f);
}
Output is : 2.537
But how?
I think output should be 2.536
but the output is 2.537
.
#include<stdio.h>
void main()
{
float f = 2.5367;
printf("%3.3f",f);
}
Output is : 2.537
But how?
I think output should be 2.536
but the output is 2.537
.
Because 2.5367 is closer to 2.537. Delta from 2.536 is 0.007 while delta from 2.537 is just 0.003.
What you want to do is just deleting last character of its string representation and is wrong in math.
In addition to existing answers, note that many C compilers try to follow IEEE 754 for floating-point matters. IEEE 754 recommends rounding according to the current rounding mode for conversions from binary floating-point to decimal. The default rounding mode is “round to nearest and ties to even”. Some compilation platforms do not take the rounding mode into account and always round according to the default nearest-even mode in conversions from floating-point to decimal.
since float f = 2.5367 needs to rounding up and there should be 3 digit after decimal, so the value will be 2.*** , means 2.537.
The documentation says:
The precision value specifies the number of digits after the decimal point. If a decimal point appears, at least one digit appears before it. The value is rounded to the appropriate number of digits.
That said, please use another book or resource for learning, whoever taught you that it's ok to use void main()
is plain wrong and should not teach C.