C++ 使用 printf() 的两位小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4784336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Two decimal places using printf( )
提问by badgerr
I'm trying to write a number to two decimal places using printf()
as follows:
我正在尝试使用printf()
以下方法将数字写入两位小数:
#include <cstdio>
int main()
{
printf("When this number: %d is assigned to 2 dp, it will be: 2%f ", 94.9456, 94.9456);
return 0;
}
When I run the program, I get the following output:
当我运行程序时,我得到以下输出:
# ./printf
When this number: -1243822529 is assigned to 2 db, it will be: 2-0.000000
Why is that?
这是为什么?
Thanks.
谢谢。
回答by badgerr
What you want is %.2f
, not 2%f
.
你想要的是%.2f
,不是2%f
。
Also, you might want to replace your %d
with a %f
;)
另外,您可能想%d
用%f
;)替换您的
#include <cstdio>
int main()
{
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;
}
This will output:
这将输出:
When this number: 94.945600 is assigned to 2 dp, it will be: 94.95
当这个数字:94.945600 分配给 2 dp 时,它将是:94.95
See here for a full description of the printf formatting options: printf
有关 printf 格式选项的完整说明,请参见此处: printf
回答by Jonathan Leffler
Use: "%.2f"
or variations on that.
使用:"%.2f"
或它的变体。
See the POSIXspec for an authoritative specification of the printf()
format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.
有关格式字符串的权威规范,请参阅POSIX规范printf()
。请注意,它将 POSIX extras 与核心 C99 规范分开。有一些 C++ 站点会出现在 Google 搜索中,但从 SO 其他地方的评论来看,至少有些站点的声誉令人怀疑。
Since you're coding in C++, you should probably be avoiding printf()
and its relatives.
由于您使用 C++ 进行编码,因此您可能应该避免使用 C++ printf()
。
回答by Rozuur
For %d
part refer to this How does this program work?and for decimal places use %.2f
对于%d
部分请参考本请问这个工作方案?和小数位使用%.2f
回答by Mike Maske
Try using a format like %d.%02d
尝试使用像 %d.%02d 这样的格式
int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);
Another approach is to type cast it to double before printing it using %f like this:
另一种方法是在使用 %f 打印之前将其类型转换为 double ,如下所示:
printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);
My 2 cents :)
我的 2 美分 :)