'summation implement in c programming output incorrect

I have to find out the sum of the given series in C programming language.

enter image description here

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 i is even, then i & 1 == 0 and the function returns 1
  • if i is odd, then i & 1 == 1 and 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