Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading