Accelerated C++<4-4>

来源:互联网 发布:两个矩阵的协方差公式 编辑:程序博客网 时间:2024/04/29 15:54

//现在,再次修改你的求平方程序,用它来求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;
}

0 0
原创粉丝点击