Home Forums C Programming Approximate the value of PI

Viewing 2 reply threads
  • Author
    Posts
    • #2133
      RandiHoltermann
      Participant

      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

      #include 
      int main (void)
      {
      int x,
      i;
      //int sum=0;
      double PI;
      float sum=0, y;

      printf("Please enter the terms of series that should be included> ");
      scanf("%d", &x);

      for (i=1; i<=x; i++){
      i=y;

      if (i%2==1) //odd

      if (sum%2==0)
      sum=sum+1/y;
      else
      sum=sum-1/y;
      }

      PI= 4*sum;
      printf("The sum is %fn", sum);
      printf("Approximate value of PI is %fn", PI);

      return 0;
      }

    • #3446
      glimpse
      Participant

      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:


      if (sum%2==0)
      sum=sum+1/y;
      else    sum=sum-1/y;
      //The I would put this part into brackets {}.if (i%2==1){   
      if (sum%2==0)
              sum=sum+1/y;

          else
              sum=sum-1/y;orif (i%2==1)
          if (sum%2==0)
              sum=sum+1/y;else    sum=sum-1/y;
    • #3447
      RandiHoltermann
      Participant

      Thanks for your input. The following is the working scripts

          #include 
      int main (void)
      {
      int x;
      float sum=0;
      double PI;

      printf("Please enter the terms of series that should be included> ");
      scanf("%d", &x);

      for (int i=1; i if (i%4==1)
      sum=sum+1./(double)i;
      else
      sum=sum-1./(double)i;

      PI= 4*sum;
      printf("The sum is %fn", sum);
      printf("Approximate value of PI is %fn", PI);

      return 0;
      }
Viewing 2 reply threads
  • The forum ‘C Programming’ is closed to new topics and replies.