Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, I have written a program for the sum of pi #include <cstdlib> #include <i

ID: 3544098 • Letter: H

Question

Hello, I have  written a program for the sum of pi


#include <cstdlib>
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double pi = 0;
    double i;
    int n;
    
    cout<<"This program approximates pi using an n-term series expansion."<<endl;
    cout<<"Enter the value of n>";
    cin>>n;
    cout<<endl;
    
    if(n <= 0)
    {
    cout<<""<<n<<" is an invalid number of terms."<<endl;
    cout<<endl;
    }
      else
      {
         for (double i = 1; i <= n; i++)
         {
         pi += pow(-1, i+1)*(4/(2*i-1));
         
         }
         cout.precision(20);
         cout<<"pi"<<"["<<n<<"]"<<" = "<<pi<<endl;
         cout<<endl;
     }
        
           
    return 0;
}


However, it only outputs the answers. it should be display just like the sample runs below.


pi[10] = 4[1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 - 1/15 + 1/17 - 1/19] = 3.04183961892940146754


Can anyone help me with this issue? It's the only problem I have.

Explanation / Answer

Three things: First, change your calculation of secondTerm for the following:

This way, you are forcing it to be a double (otherwise, it would return an int, which we do not want). Second, change this line:

for this line:

That is because secondTerm holds the result of the division, not the denominator.

Third, move this line:

after the for loop, because that prints the final result, which you would do after you sum all the terms.Having that line inside the for is causing the line breaks. If you do this, you will need to move this line:

before the for loop, so the sum variable continues to exist afterwards.

If you do all this, the program will work fine (although it prints all the terms without any spaces between them).

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote