简体   繁体   English

如何限制 printf 在小数点后显示的位数?

[英]How can I limit the number of digits displayed by printf after the decimal point?

I wrote a small program that reads two integers using scanf and then performs various arithmetic calculations.我写了一个小程序,它使用scanf读取两个整数,然后执行各种算术计算。 I'm using printf to display the results.我正在使用printf来显示结果。 How can I make printf display only two digits after the decimal point?如何让printf只显示小数点后两位? Starting with the simplified code sample:从简化的代码示例开始:

#include <stdio.h>

int main(void)
{
    double third = 1.0 / 3.0;

    // display data  
    printf("\n%20s%20s", "Description", "Data");
    printf("\n%20s%20s", "-----------", "----");
    printf("\n%20s%20lf", "One third", third);
    printf("\n");
    return 0;
}

This prints "0.333333" for the value of third .这将打印“0.333333”作为third值。 How would I alter the above to get the following output?我将如何更改上述内容以获得以下输出?

\n         Description Data描述数据\n         ----------- ---- ----------- ----\n           One third 0.33三分之一 0.33\n

use "%.2f" at the place you want.在你想要的地方使用“%.2f”。

For example, modify the following statement比如修改下面的语句

printf("\n%20s%20lf", "Fraction", quotientdecimal);

into this one :进入这个:

printf("\n%20s%.2f", "Fraction", quotientdecimal);

will only display two fraction numbers of the variable quotlentdecimal.将只显示变量 quotlentdecimal 的两个小数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM