Function calculates to some extent and for

2

I have a double variable making an account but it reaches a limit [in my case 1.367879] and it does not increase any more.

The code is running normally, the problem is the result that is no more than 1.367879

#include <stdio.h>
#include <stdlib.h>

double calcSoma(int n);
long int fatorial(int n);

int main () {
    int termos;
do {
    printf("Digite a qtd de termos (>= 5): ");
    scanf("%d", &termos);
}while(termos < 5);
 printf("\nO somatorio para %d termos eh %f", termos, calcSoma(termos));

}

double calcSoma (int n){
    double s = 1;
    int i, numerador = 0, valFat = 1;
    for (i = 0; i < n; i ++) {
        numerador = numerador + 2;
        valFat = valFat + 2; //numeros impares
        s = s + (double)numerador/fatorial(valFat);
    }
return s;
}

long int fatorial(int n){
    long int fat = 0;
    if (n == 0) {
        return 1;
    }else {
        fat = n * (fatorial(n-1));
    }
    return fat;
}
    
asked by anonymous 31.05.2016 / 02:30

2 answers

2

In the calcSoma() function, the value that you add to s becomes smaller very fast.

numerador / fatorial(valFat) is a number getting closer to zero.

1.367879 + 0.0000000000000....0006576423 never leaves 1.367879

Value added to s with

i = 0; // numerador/fatorial(valFat) ==  2/ 3!  == 0.333...
i = 1; // numerador/fatorial(valFat) ==  4/ 5!  == 0.0333...
i = 2; //                                6/ 7!  == 0.00119...
i = 3; //                                8/ 9!  == 0.0000220...
i = 4; //                               10/ 11! == 0.000000250...
i = 5; //                               12/ 13! == 0.00000000192...
    
31.05.2016 / 14:25
1

There is a limit of the number that can be represented by the numeric types, this formula is working with numbers too large. You need to create or use something ready to deal with such great values. Which is not an easy thing to do. My suggestion is to use GMP .

Changing the formatting to display the number in scientific notation helps you see the number better (in this case not much).

    
31.05.2016 / 02:43