//如果重写上题的程序,让它计算从1到999的整数的平方。但是,我们忘记了更改setw的参数的值。会出现什么问题呢?重写这个程序,让它具有更好的适应性,重新写后的程序应实现这样的目标:当i增长时不需要修正setw的参数。
Hint
Determine the length of the longest base and longest result and store those maximum lengths before starting to send the results to output.
Solution
If we change the program to output squares of bases up to 999 but don’t change the values provided to setw, the columns will begin to run together when the number of digits in the squares begins to equal 6.
#include <iomanip>
#include <iostream>
using namespace std;
/* Return the number of digits in n */
int digits(int n)
{
int result = 0;
while (n)
{
/* Add 1 to the result... */
++result;
/* ...and remove a digit before the next pass. */
n /= 10;
}
return result;
}
int main()
{
const int max_base = 999;
/* Find the number of digits in the highest base. */
int max_base_width = digits(max_base);
/* Find the number of digits in the highest square. */
int max_result_width = digits(max_base * max_base);
for (int i = 1; i <= max_base; ++i)
{
/* Add 1 to the maximum widths to allow for one
space for padding. */
cout << setw(max_base_width + 1) << i
<< setw(max_result_width + 1) << (i * i) << endl;
}
}
//或者
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int get_width(int n) {
return log10(n) + 1;
}
int main() {
int max = 100;
for (int i = 1; i <= max; ++i) {
cout << setw(get_width(max))
<< i
<< setw(get_width(max * max) + 1)
<< i * i
<< endl;
}
return 0;
}