1.取整问题
操作 | 描述 |
---|---|
floor | 向下取整 |
ceil | 向上取整 |
round | 四舍五入取整 |
以上函数均包含在 cmath
头文件中。
示例:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x = 14.78;
double y = 21.32;
cout << "floor: " << floor(x) << " " << floor(y) << endl;
//floor: 14 21
cout << "ceil: " << ceil(x) << " " << ceil(y) << endl;
//ceil: 15 22
cout << "round: " << round(x) << " " << round(y) << endl;
//round: 15 21
return 0;
}
2. 输出数值格式问题
操作 | 描述 |
---|---|
setprecision(n) | 设定一个浮点数的精度 |
fixed | 显示指定小数点位数的浮点数 |
showpoint | 即使没有小数部分也显示以零补足的小数点后位数 |
setw(width) | 指定打印字段的宽度 |
left | 调整输出到左边 |
right | 调整输出到右边 |
以上函数包含在iomanip
头文件中。
示例:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double x = 14.7823;
double y = 738847294.23;
//setprecision(n)单独使用,显示的位数总和为n(小数点前后位数总和)
cout << setprecision(3) << x << endl; //14.8
//计算机会用科学计数法显示一个很长的浮点数,fixed强制数字显示为非科学计数法的形式
cout << y << endl; //7.39e+008
cout << fixed << y << endl; //738847294.230
//fixed与setprecision(n)一起使用,显示小数点后n位
cout << fixed << setprecision(3) << x << endl; //14.782
cout << showpoint << y << endl; //738847294.230
cout << setw(4) << "C++" << setw(6) << 101 << endl; // C++ 101
cout << right;
cout << setw(4) << "C++" << setw(6) << 101 << endl; // C++ 101
cout << left;
cout << setw(4) << "C++" << setw(6) << 101 << endl;//C++ 101
return 0;
}