如何显示从0到浮点值中多少个小数的小数位?

问题描述 投票:0回答:1

我正在使用C,并且我正在尝试以以下格式打印pi的值:33.13.143.1453.1459等等但是我不确定该怎么做吗?

c
1个回答
1
投票
#include <float.h>  //  For floating-point characteristics, notably DBL_DIG.
#include <stdio.h>


int main(void)
{
    static const double pi = 3.1415926535897932384626433;

    /*  Iterate through number of digits to display, up to number of decimal
        digits that double is guaranteed to preserve through round trip.
        (Note that DBL_DIG is the number of significant digits for that purpose,
        so DBL_DIG-1 is the number after the decimal point given that we have
        one digit, 3, before the decimal point.)
    */
    for (int i = 0; i < DBL_DIG; ++i)

        /*  Print with the number of digits specified in an argument.  An
            asterisk in a format field says to take the number that would be
            there from the parameters, and the number after "." in an "f"
            specification says how many digits to show after the decimal point.
        */
        printf("%.*f\n", i, pi);
}

输出:

33.13.143.1423.14163.141593.1415933.14159273.141592653.1415926543.14159265363.141592653593.1415926535903.14159265358983.14159265358979
© www.soinside.com 2019 - 2024. All rights reserved.