Accelerated C++<4-4>

//现在,再次修改你的求平方程序,用它来求double类型而不是int类型的值的平方。使用控制器控制输出,让数值按列排列起来。




Hint

Allow for fractional values, and change how you determine the number of digits in the highest base and square.


Solution

First, we’ll make a change to the digits function to allow for the number of decimal places we want to see on the final outputs. Next, we’ll use the setprecision manipulator to control the number of significant digits in the output.



#include <iomanip>
#include <iostream>
 
using std::cout;
using std::endl;
using std::setw;
using std::setprecision;
 
/* Return the number of digits in n */
int digits(double n, int places)
{
   /* Initialize result to the number of desired decimal 
   places. */
   int result = places;
 
   while (n >= 1)
   {
      /* Add 1 to the result... */
      ++result;
 
      /* ...and remove a digit before the next pass. */
      n /= 10;
   }
 
   return result;
}
 
int main()
{
   const double max_base = 99.9;
 
   /* Find the number of digits in the highest base. */
   int max_base_width = digits(max_base, 2);
 
   /* Find the size of the highest square, allowing for 
   2 decimal places in the result. */
   int max_result_width = digits(max_base * max_base, 2);
   
   for (double i = 1; i <= max_base; i += .1)
   {
      /* Add 2 to the maximum widths to allow for the decimal point and 
      one space for padding. */
      cout << setw(max_base_width + 2) << 
         setprecision(max_base_width) << i 
         << setw(max_result_width + 2) 
         << setprecision(max_result_width) << (i * i) << endl;
   }
}




//或者


#include <cmath>
#include <iomanip>
#include <iostream>


using namespace std;


int get_width(double n) {
  return log10(n) + 1;
}


int main() {
  double max = 1000.0;
  
  for (double i = 1.0; i <= max; ++i) {
    cout << setw(get_width(max))
<< i
<< setw(get_width(max * max) + 1)
<< i * i
<< endl;
  }
  
  return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值