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

社会主义新天地 提交于 2019-12-18 05:54:39

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/7425030/how-can-i-limit-the-number-of-digits-displayed-by-printf-after-the-decimal-point

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!