Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

c - Why is my program only printing to 6 decimal places?

Ive created a program to compute the value of an integral from zero to infinity, however when i go to print my answer it only prints it to 6 decimal places, could someone advise on why this is?

Thanks very much in advance :)

#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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is because you use string format %f which is by default only print 6 digit after comma. To increase it, simply specify the length that you want:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...