I encountered this snippet but couldn't understand how it works, especially the printf
statements. Can someone explain
void remove_trailing_zeroes()
{
int a,b;
bool f1,f2;
f1=a%2;
f2=b%2;
if (f1==f2) {
printf("%.0lf\n",(a*1.+b)/2.);
}
else {
printf("%.1lf\n",(a*1.+b)/2.);
}
}
EDIT: I have rephrased my question, help me improve it
If you are puzzled about the dots here is what they are:
%.1lf
is the format specification for precision. This is requesting one digit after the decimal point in the printf
output.1.
and 2.
in (a*1.+b)/2.
mean that those literals are double
(as opposed to 1
that would be int
and 1.f
that would be float
). Whoever wrote that snippet was probably trying to avoid truncation in computing that average (given a
and b
are int
).Sounds like:
printf("%g", (a+b)/2.);
emulation.
It looks like it prints average value between a
and b
.
This if decides when the result will need decimal point .5
:
bool f1,f2;
f1=a%2;
f2=b%2;
if (f1==f2)
It would be better to just write:
// get a and b from somewhere
if ((a+b)%2) // check if sum can be divided by 2
printf("%.1lf\n",(a+b)/2.); // %.1lf will print value with 1 decimal ("xX.X")
else
printf("%.0lf\n",(a+b)/2.); // %.0lf will print value without decimals ("xX")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.