Three things:
- You overwrite the value of
soma
every iteration of the loop;
- You define
soma
as a whole;
- You must first multiply the
fat
, then add up;
To correct (1), you will need to change soma =
for soma +=
. Already to fix the (2) just set soma
as float
. Item (3) needs to be done because otherwise you will have 2 times the denominator equal to 1. fat
starts at 1, generating the term (x+1)/1! , then it is multiplied by i
which is also 1, generating in the next iteration (x+2)/1!. In the next iteration it would be (x+3)/2! , etc. That is, the result would be different than expected.
#include <stdio.h>
int main(){
float x = 0.0;
int n = 0;
float soma = 0;
int fat = 1;
printf("Digite um valor:");
scanf("%f", &x);
printf("Digite a quantidade de operações:");
scanf("%d", &n);
for(int i = 1; i <= n; i++){
fat = fat * i;
soma += (x + i)/fat;
}
printf("A soma n pra S = x+n/n!\nÉ: %f", soma);
return 0;
}
Question: does the sum have only 4 terms even or should all terms between 3 and n be summed as well? The way you’ve posted jumps from 3 to n.
– Woss
And it shouldn’t be
soma += (x + i)/fat
? The way you override the value with each iteration.– Woss
The sum of the terms starts from 1 to n which is the number of terms chosen for example 5, went to 3 to show how it would be from the beginning of the calculation
– H.Savvy
Anderson applied the attribution operator by addition that was missing, but still continues with a wrong result
– H.Savvy
Marvin, are you sure
soma
will always be an integer?– Woss
I already changed the type to accept floats values, thank you!
– H.Savvy