Phillip Boudreau Phillip Boudreau - 28 days ago 8
C++ Question

Trouble displaying a specific number in a loop without scientific notation in C++

Ok, so I'm writing a program, of which the overall purpose is not necessarily important, but there is a point in the program where I'm trying to print out a table that displays n, n!, and x^n (where n and x are both user inputs).

The code I have thus far is as follows:

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main()
{
float x, xn, factorial = 1;
float n = 1;

cout << "Enter an angle in radians: ";
cin >> x;
while (n <= 1)
{
cout << "Enter the number of terms to be included into the Taylor series expansion: ";
cin >> n;
if (n < 1)
{
cout << "Error! Try again\n";
}
}

cout << "n\tn!\tx^n\t\n";
for (int i = 1; i <= n; i++)
{
cout << i;
factorial *= i;
cout << "\t" << factorial;
xn = pow(x, i);
cout << "\t" << setprecision(i) << xn;
cout << endl;

}

return 0;
}


Now, the problem I'm having is that it begins to display my x^n in scientific notation after it goes past 5 decimal places. I do not want it to do this. I tried using setprecision(i) as you might have noticed, but that doesn't do the job. It's confusing me because a.) I'm not sure I know the code I need to use to get it to stop displaying in scientific notation and b.) I don't want the other outputs for n and n! to be affected by the manipulation I'm going to have to use on the output of x^n, which is tricky for me because they're all calculated and outputted in the same loop. I'm at a loss here, any help is much appreciated! I'd post an image of the program output for you all, but it seems I need more reputation to do that.

Also, on a side note, if you have any advice on a better way to format my table, I'd love to hear it.

Answer Source

Before you print xn, you can switch the stream to use fixed notation, and after it, switch back to default float:

cout << "\t" << setprecision(i) << std::fixed << xn << std::defaultfloat;

References: http://en.cppreference.com/w/cpp/io/manip/fixed