用printf两位小数() [英] Two decimal places using printf( )

查看:460
本文介绍了用printf两位小数()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用写一个数字,小数点后两位的printf()如下:

I'm trying to write a number to two decimal places using printf() as follows:

#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

这是为什么?

感谢。

推荐答案

您需要的是%。2F ,而不是 2%F

此外,您可能想用%F 来取代你的%d个;)

Also, you might want to replace your %d with a %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;
}

在这里看到的printf的格式选项的完整描述: 的printf

这篇关于用printf两位小数()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆