[英]Dots in printf in C++
I encountered this snippet but couldn't understand how it works, especially the printf
statements.我遇到了这个片段,但无法理解它是如何工作的,尤其是
printf
语句。 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. %.1lf
是精度的格式规范。 This is requesting one digit after the decimal point in the printf
output.printf
输出中要求小数点后一位。1.
and 2.
in (a*1.+b)/2.
1.
和2.
中(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
).double
(而不是1
是int
, 1.f
是float
)。 Whoever wrote that snippet was probably trying to avoid truncation in computing that average (given a
and b
are int
).a
和b
是int
)。Sounds like:听起来好像:
printf("%g", (a+b)/2.);
emulation.仿真。
It looks like it prints average value between a
and b
.看起来它打印
a
和b
之间a
平均值。
This if decides when the result will need decimal point .5
:这决定了结果何时需要小数点
.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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.