The problem I am having is that I can\'t seem to get the output to line up. The
ID: 3660167 • Letter: T
Question
The problem I am having is that I can't seem to get the output to line up. The decimals are supposed to be in the same column and the headers should be lined up above each column.
Here is a picture of the output:
/*Synopsis: Reads in the number of roots, a value to increment, the operand, and a value
for the precision of the output. The program will output a table of roots for the given number of roots and values
of x equal to 'i' times the increment up to and including 100. */
#include <iomanip>
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
double n; //Number of roots
double v; //Value to increment the base
int p; //Precision
double x;
cout << "Enter the number of roots: "; //Input number of roots
cin >> n;
cout << "Enter the value to increment the base: "; //Input the value to increment the bases (x)
cin >> v;
cout << "Enter the precision: "; //Enter precision of the root calculation
cin >> p;
int width = 7+p; //Declare the width to be an integer
cout.setf(ios::fixed); //Fixing the precision
cout.precision(p); //Diplaing the precision to be based on precision input
cout << "Value" ; //Displaying the Value header
for (int i=2; i<=n+1; i++) //For loop that creates the column headers of the roots
{
double x=i;
cout << setw(width) << "x^1/" << i; //Outputs the column headers based on the user inputted number of roots
}
cout << endl;
for (double x=v; x<100; x=x+v) //Outer for loop which sets up the rows to be looped and for the value
{
cout << x; //This outputs the values in the first column. Number that's being rooted.
for (double i=2; i<=n+1; i++) //Inner for loop
{
cout << setw(width) << pow(x,1/i); //Outputs the calculated root
}
cout << endl;
}
for (int i=1; i==100; i++) //For loop that outputs the value if it is equal to 100.
{
cout << setw(width) << pow(x,1/i);
}
cout << endl;
return 0;
}
Explanation / Answer
To fix the allignment of the first few values a minor change is needed. Where you displace your values just add in a if condition that if its smaller than 10 it'll add a space before the cout.
if(x < 10)
cout << " " << x;
else
cout << x;
The header unallignment is due to your setw(width).
To fix the allignment you need to add it also when you cout << "Value" and change the setw(width) for the header display.
cout << setw(width-4) << "Value" ;
cout << setw(width-1) << "x^1/" << i;
Enjoy! ^^
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.