You are here:

C++/help please

Advertisement


Question
this is the formula my teacher wants us to follow
p = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...and so on
we have to write a program that asks the user to enter how many terms they want to use. meaning if they enter 3, the out put should show

term          approximation
1          4
2          (the answer to 4 - 4/3)
3          (the answer to 4 - 4/3 + 4/5)

i can only understand to add all of them but i cant alternate with the subtracting, then adding.. please help if u can

this is the code that i have so far:

#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
  int n, x, i;
  int num;
  double den, r, total=0;


  cout << "How many terms do you want to use?\n";
  cin >> i;
  
  cout << setw(6) << "Term" << setw(23) <<"Approximation" << endl;
  

  for (n=1; n<=i; n++)

  {
     for (x=1, num = 4, den = 1; x <= n; x++, den+=2)
         
        r = (num/den);
        total += r;
         
     cout << setw(4) << n;
     cout << setw(20) << total << endl;
}
  return 0;
}

Answer
Dear Donald !

You have done almost but the only thing wrong is that this series calculate all terms as positive but waht actuallully have to do is the odd and even term should have opposite sign

This can be acchieved by inserting a sign data which toggles between bth +ve and -ve

ie
 total += r; may be modified as follows

 total = total + (sign)* r;
 sign = sign * -1;

In the same for loop


Note !
Yuo have to do initialization of the integer sign like this
int sign = 1;

Regards !
Prince M.Premnath  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise

Years of research in C/C++ Will bring you all facts regarding , OOPS , SVGA , MOUSE , BIOS , IVT , Feel free to query me :-)

Experience

More than 5 years

Education/Credentials
MCA

©2016 About.com. All rights reserved.