Accelerated C++<4-3>

//如果重写上题的程序,让它计算从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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值