coding integral with C

Viewed 59
#include<stdio.h>
int F(int);
int g(int,int);
int n;
float f[100];
int main(){
    printf("적분 구간 ");
    int a,b;
    scanf("%d",&a);
    scanf("%d",&b);
    printf("\n차수 ");
    scanf("%d",&n);
    for(int i=n;i>=0;i--){
        printf("\n%d차항 계수 ",i);
        scanf("%f",&f[i]);
    }
    for(int i=n;i>=0;i--){
        f[i+1]=f[i]/(i+1);
    } 
    float s=F(b)-F(a);
    printf("%d",s);
}



int F(int x){
    float ret=0;
    for(n=n+1;n>=1;n--) ret+=g(n,x);
    return ret;
    }
    
    
    
int g(int k,int l){
    float y=1;
    for(int t=1;t<=k;t++) y=y*l;
    y=f[k]*y;
    return y;
}

I am trying to make code that can calculate integral. But code is giving the same result, which is 0. It would be great if you let me know what is wrong with my code.

1 Answers

Your F and g are returning int but should be returning float. Returning int instead of float will result in truncation of all decimals, leading to incorrect results.

float s=F(b)-F(a);

would quite possibly become 0.

Declare the functions as:

float F(int);
float g(int,int);

Also, you are printing the floating point variable s as an int:

float s=F(b)-F(a);
printf("%d",s);

Change the %d to %f.

Related