如何限制小数点后的printf显示的数字位数? [英] How can I limit the number of digits displayed by printf after the decimal point?

查看:551
本文介绍了如何限制小数点后的printf显示的数字位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小程序,使用 scanf函数读取两个整数,然后执行各种算术运算。我使用的printf 来显示结果。我怎样才能让的printf 显示只有两个数字的小数点后?与简化的code的样品开始:

 的#include<&stdio.h中GT;INT主要(无效)
{
    第三双= 1.0 / 3.0;    //显示数据
    的printf(\\ N%20年代20年代%,说明,数据);
    的printf(\\ N%20年代20年代%,-----------,----);
    的printf(\\ N%20年代%20lf,三分之一,第三);
    的printf(\\ n);
    返回0;
}

这版画0.333333为的值第三。我将如何改变上面得到下面的输出?


         说明数据
         ----------- ----
           三分之一0.33


解决方案

使用%.2f在你想要的地方。

例如,修改下面的语句

 的printf(\\ N%20年代%20lf,分数,quotientdecimal);

到这一个:

 的printf(\\ N%20年代%.2f,分数,quotientdecimal);

将只显示变量quotlentdecimal两个比例数字。

I wrote a small program that reads two integers using scanf and then performs various arithmetic calculations. I'm using printf to display the results. How can I make printf display only two digits after the decimal point? 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. How would I alter the above to get the following output?

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

解决方案

use "%.2f" at the place you want.

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.

这篇关于如何限制小数点后的printf显示的数字位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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