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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7425030/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:38:21  来源:igfitidea点击:

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

cdecimal

提问by Sarah Dawkins

I wrote a small program that reads two integers using scanfand then performs various arithmetic calculations. I'm using printfto display the results. How can I make printfdisplay only two digits after the decimal point? Starting with the simplified code sample:

我写了一个小程序,它使用读取两个整数scanf,然后执行各种算术计算。我printf用来显示结果。如何让printf小数点后只显示两位数?从简化的代码示例开始:

#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. How would I alter the above to get the following output?

这将为 的值打印“0.333333” third。我将如何更改上述内容以获得以下输出?

         Description                Data
         -----------                ----
           One third                0.33
         Description                Data
         -----------                ----
           One third                0.33

回答by Derrick Zhang

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 的两个小数。