'summation implement in c programming output incorrect
I have to find out the sum of the given series in C programming language.
As per the formula if n=1 then the output should be 4(2/3)= 8/3
The c programming code that I have written:
#include <stdio.h>
int main() {
int n, i;
float sum = 0;
printf("Enter the value of n: ");
scanf("%d", &n);
for (i = 0; i <= n; i++) {
sum = sum + 4 * ((-1) ^ i / ((2 * i) + 1));
}
printf("Sum of the series: %f", sum);
return 0;
}
I got the output -8.
What I did wrong in my code?
Thank you.
Solution 1:[1]
One small optimization to the answer above:
You don't really need standard function pow in order to calculate powers of -1.
Instead, you can use:
int minusOnePow(int i) {
return 1 - 2 * (i & 1);
}
Explanation:
- if
iis even, theni & 1 == 0and the function returns1 - if
iis odd, theni & 1 == 1and the function returns-1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | bbbbbbbbb |

