Link to home
Start Free TrialLog in
Avatar of ViperX883
ViperX883

asked on

How do I return to the default settings for cout once I have set a precision?

In a program I set the precision of the cout function to n where n is an integer value. However, later I would like to output values with the default cout settings, i.e. I want to undo what I did to the precision. I'm not sure how to do this and would appreciate any help. A copy of the code I'm using is below.

void Newton(Poly f)
{
  Poly g = f;
  int maxIter = 100;
  int i, precision;
  double guess, previous, guessRound, previousRound;

  // Prompt user to enter an initial guess

  cout << "Please enter your initial guess: ";
  cin >> guess;

  // Prompt user to enter the desired precision

  cout << "Enter your desired precision (up to 20 decimal places): ";
  cin >> precision;

  if(precision < 0 || precision > 20)
    cout << "\nI'm sorry, you have entered an incorrect precision.";

  else if(f.eval(guess) == 0)
    {
      cout << "\nYour guess, " << guess << ", is a root to the equation." << endl;
    }

  else
    {
      // Take derivative of original function

      f.derivative();

      // Set the output precision to user's specification

      cout.setf(ios::fixed, ios::floatfield);
      cout.setf(ios::showpoint);
      cout.precision(precision);

      previous = guess;

      // Use a for loop to perform several iterations of Newton's method.
      // Check for precision and terminate loop when it is reached.

      for(i=1; i<=maxIter; i++)
        {
          guess = previous - (g.eval(previous)/f.eval(previous));

          guessRound = round(guess, precision);
          previousRound = round(previous, precision);

          if(guessRound == previousRound)
            break;
          else
            previous = guess;
        }

      if(guessRound == previousRound)
        cout << "\nAfter " << i << " iterations, the root was found to be " << guessRound << "." << endl;
      else
        cout << "\nI'm sorry, after 100 iterations a root was not found." << endl;
}

Thanks to anyone who can help.
Avatar of Kimpan
Kimpan
Flag of Sweden image

why don't you save the old precision before you set the new one?
Avatar of ViperX883
ViperX883

ASKER

I read somewhere that I would have to save the precision, but the problem is I have absolutely no idea how to do that. I have tried several times to develop classes and functions, but to no avail.

Thanks again for all the help.
ASKER CERTIFIED SOLUTION
Avatar of Kimpan
Kimpan
Flag of Sweden image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial