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 <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;
}
- Accelerated C++<4-4>
- Accelerated C++<4-1>
- Accelerated C++<4-2>
- Accelerated C++<4-3>
- Accelerated C++<4-5>
- Accelerated C++<4-6>
- Accelerated C++<4-7>
- accelerated 2-5-4
- Accelerated C++ Exercise 4-4
- Accelerated C++ exercises 4-0
- Accelerated C++ Exercise 4-2
- Accelerated C++ Exercise 4-1
- Accelerated C++ Exercise 4-3
- Accelerated C++ Exercise 4-5
- Accelerated C++学习笔记4
- Accelerated C++:通过示例进行编程实践——练习解答(第4章)
- 读《Accelerated C++》有感
- 【Accelerated C++】读书笔记(一)
- hdu1285 确定比赛名次(拓扑排序)
- 旋转数组的最小数字
- PAT_A 1036. Boys vs Girls (25)
- Java虚拟机(HotSpot)对象
- 良心推荐十款堪称神器的软件
- Accelerated C++<4-4>
- Vue.js之devtools
- 19. 标准函数库
- 信息熵
- 【java】简单的双人五子棋
- Java基础之线程(1)
- 配置Ubuntu环境一些简记
- python3字典排序
- RecyclerView进阶(二)点击事件的实现