gpt4 book ai didi

c++ - 使用 printf() 保留小数点后两位

转载 作者:IT老高 更新时间:2023-10-28 13:23:32 24 4
gpt4 key购买 nike

我正在尝试使用 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;
}

当我运行程序时,我得到以下输出:

# ./printf
When this number: -1243822529 is assigned to 2 db, it will be: 2-0.000000

这是为什么呢?

谢谢。

最佳答案

你想要的是 %.2f,而不是 2%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;
}

这将输出:

When this number: 94.945600 is assigned to 2 dp, it will be: 94.95

有关 printf 格式化选项的完整说明,请参见此处:printf

关于c++ - 使用 printf() 保留小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4784336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com