21xrx.com
2025-03-29 14:03:10 Saturday
文章检索 我的文章 写文章
C++如何输出小数点
2023-06-24 09:19:28 深夜i     25     0
C++输出 小数 格式化 iomanip 精度

在C++中,输出小数点可以通过使用cout语句配合iomanip库的setprecision()函数来实现。setprecision()函数可以设置小数点后的位数,具体使用方法如下:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
  double num = 3.1415926;
  cout << "原始数字:" << num << endl;
  cout << "输出小数点后3位:" << setprecision(3) << num << endl;
  cout << "输出小数点后5位:" << setprecision(5) << num << endl;
  return 0;
}

运行该程序,输出结果为:

原始数字:3.14159
输出小数点后3位:3.14
输出小数点后5位:3.14159

需要注意的是,setprecision()函数只对接下来的输出有效,输出后会自动恢复到默认精度。另外,C++中的浮点数存在精度误差的问题,因此在计算时应当避免进行精度要求较高的运算,或者使用特殊的浮点数库来处理。

  
  

评论区