I'm having trouble with Exercise 4-2 in Accelerated C++. The exercise
is "Write a program to calculate the squares of int values up to 100.
The program should write two columns: The first lists the value; the
second contains the square of that value. Use setw to manage the
output so that the values line up in columns."
Something similar is listed below, But the columns should be able to
line up no matter what the value of max is. The way it is now it goes
to around 30,000 to 40,000 then the columns lose their lining, so I
figured this obviously isn't the way to do it.
#include <iomanip>
#include <iostream>
int main()
{
int cwidth = 0;
int i2 = 0;
int max = 100;
for (int i = 0; i <= max; i++)
{
i2 = i*i
if (i2 < 10) {
cwidth = 9;
} else if (i2 >=10 && i2 < 1000) {
cwidth = 10;
} else if (i2 >= 1000) {
cwidth = 11;
}
std::cout << i << std::setw(cwidth) << i2 << std::endl;
}
}
is "Write a program to calculate the squares of int values up to 100.
The program should write two columns: The first lists the value; the
second contains the square of that value. Use setw to manage the
output so that the values line up in columns."
Something similar is listed below, But the columns should be able to
line up no matter what the value of max is. The way it is now it goes
to around 30,000 to 40,000 then the columns lose their lining, so I
figured this obviously isn't the way to do it.
#include <iomanip>
#include <iostream>
int main()
{
int cwidth = 0;
int i2 = 0;
int max = 100;
for (int i = 0; i <= max; i++)
{
i2 = i*i
if (i2 < 10) {
cwidth = 9;
} else if (i2 >=10 && i2 < 1000) {
cwidth = 10;
} else if (i2 >= 1000) {
cwidth = 11;
}
std::cout << i << std::setw(cwidth) << i2 << std::endl;
}
}