21xrx.com
2025-06-26 04:52:02 Thursday
登录
文章检索 我的文章 写文章
C++如何控制输出的小数点位数
2023-07-07 07:43:23 深夜i     27     0
C++ 控制 输出 小数点 位数

在C++编程中,输出小数时有时需要控制其小数点位数,这时可以使用iomanip库中的setprecision函数来实现。

setprecision函数需要一个整数参数,表示小数点后要显示的位数。例如,以下代码将输出变量a的小数点后两位:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
  double a = 3.1415926;
  cout << setprecision(2) << a << endl;
  return 0;
}

输出:

3.14

需要注意的是,setprecision函数只能控制输出的精度,不能进行四舍五入。如果需要进行四舍五入,可以使用math库中的round函数,将小数乘以10的n次方(n为小数点位数),进行四舍五入后除以10的n次方。

以下是一个完整的示例代码:

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
  double a = 3.1415926;
  int n = 2; //小数点后两位
  cout << "原数:" << a << endl;
  a *= pow(10, n);
  a = round(a);
  a /= pow(10, n);
  cout << "四舍五入后:" << a << endl;
  cout << "精度控制后:" << setprecision(n) << a << endl;
  return 0;
}

输出:

原数:3.14159
四舍五入后:3.14
精度控制后:3.14

通过setprecision函数和round函数的组合运用,我们可以方便地控制小数点位数输出,并且可以进行四舍五入的处理。

  
  

评论区