【问题标题】:Why is my program only printing to 6 decimal places?为什么我的程序只打印到小数点后 6 位?
【发布时间】:2016-06-10 22:41:33
【问题描述】:

我创建了一个程序来计算从零到无穷大的积分值,但是当我打印我的答案时,它只打印到小数点后 6 位,有人能告诉我这是为什么吗?

非常感谢:)

#include <stdio.h>
#include <math.h>
#include <float.h>

double integral_Function(double x){
    double value;
    value = 1/((1+ pow(x, 2))*(pow(x, 2/3)));
    return value;
}

double trapezium_Rule(double lower, double upper, int n){

    double h;
    double total;

    h = (upper - lower)/n;

    total = (h/2) * (integral_Function(upper) + integral_Function(lower));

    for(int i = 1; i < n; i++){
        total = total + (h * integral_Function(lower + (i * h)));
    }

    return total;

}

int main() {

    double sum = 0;
    double upper = DBL_MIN * 1.001;
    double lower = DBL_MIN;

    while (upper <= DBL_MAX){
        sum +=  trapezium_Rule(lower, upper, 5000) * 2;
        lower = upper;
        upper = upper * 1.02;
    }


    printf("%f", sum);

    return 0;
}

【问题讨论】:

  • 六位小数是 %f (Source) 的默认精度。

标签: c printf double decimal-point


【解决方案1】:

这是因为您使用字符串格式%f,默认情况下仅在逗号后打印 6 位数字。要增加它,只需指定您想要的长度:

printf("%.9f", sum); //note the 9 - it is the length.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 2017-12-31
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    相关资源
    最近更新 更多