Home › Forums › C Programming › Approximate the value of PI

- This topic has 2 replies, 2 voices, and was last updated 12 years, 7 months ago by RandiHoltermann.

Viewing 2 reply threads

- AuthorPosts
- September 4, 2008 at 1:01 am #2133RandiHoltermannParticipant
Hi guys. I’m pretty new to C program. I’ve been given this assignment to write a program that asks the user thow many terms of the serires equation to use in approximating PI. The formula given is pi=4X(1- 1/3 + 1/5 – 1/7 + 1/9 – 1/11 + 1/13 – ….)

Here is the script that I’ve written but I’m stuck. Please advice. My alogarithm might be wrong

123456789101112131415161718192021222324252627282930#include <stdio.h><br />int main (void)<br />{<br />int x,<br />i;<br />//int sum=0;<br />double PI;<br />float sum=0, y;<br /><br />printf("Please enter the terms of series that should be included> ");<br />scanf("%d", &x);<br /><br />for (i=1; i<=x; i++){<br />i=y;<br /><br />if (i%2==1) //odd<br /><br />if (sum%2==0)<br />sum=sum+1/y;<br />else<br />sum=sum-1/y;<br />}<br /><br />PI= 4*sum;<br />printf("The sum is %fn", sum);<br />printf("Approximate value of PI is %fn", PI);<br /><br />return 0;<br />}<br /> - September 4, 2008 at 2:03 am #3446glimpseParticipant
I don’t understand so much from mathemics, but a problem migth be, that your variable i is an integer value.

Something else: What should happen, if (i%2==1) ?

I expect you mean the hole part:12345678910111213<br />if (sum%2==0)<br />sum=sum+1/y;<br />else sum=sum-1/y;<br />//The I would put this part into brackets {}.if (i%2==1){ <br />if (sum%2==0)<br />sum=sum+1/y;<br /><br />else<br />sum=sum-1/y;orif (i%2==1)<br />if (sum%2==0)<br />sum=sum+1/y;else sum=sum-1/y;<br /> - September 4, 2008 at 5:32 am #3447RandiHoltermannParticipant
Thanks for your input. The following is the working scripts

12345678910111213141516171819202122#include <stdio.h><br />int main (void)<br />{<br />int x;<br />float sum=0;<br />double PI;<br /><br />printf("Please enter the terms of series that should be included> ");<br />scanf("%d", &x);<br /><br />for (int i=1; i<x; i+=2)<br />if (i%4==1)<br />sum=sum+1./(double)i;<br />else<br />sum=sum-1./(double)i;<br /><br />PI= 4*sum;<br />printf("The sum is %fn", sum);<br />printf("Approximate value of PI is %fn", PI);<br /><br />return 0;<br />}

- AuthorPosts

Viewing 2 reply threads

- The forum ‘C Programming’ is closed to new topics and replies.