Skip to main content

ex8.cpp


// Solution to Exercise 8
// (NDE, 2014-01-03)
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
  int n = 1;
  cout << fixed << setprecision(3);
  while (n <= 20) {
    cout << setw(3) << n;
    cout << setw(8) << sqrt(n) << endl;
    ++n;
  }
  return 0;
}

Notice the initial use of cout, before the loop. This is done to set up the stream for output of floating-point numbers to three decimal places. These stream manipulators could be used in the output statements within the loop, but the operations would then be repeated unnecessarily for each value written to the stream. (Remember that stream manipulations such as setprecision are persistent; once applied, they remain in force until explicitly reset or changed.)