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.
CodePudding user response:
The ^
operator in C is exclusive-or, not exponentiation. There is no exponentiation operator, but you could think about how to get the effect of (-1)^i
with other operators, such as ?:
. (You may see advice to use the pow
function, but it's for floating point, not integers, and so is not a good drop-in.)
The other problem is that dividing two integers does integer division, which truncates any fractional part. You'll need to cast either the numerator or denominator to float
or double
before dividing. (Generally double
is a better choice than float
, except if you have a large array whose memory usage is significant.)