21xrx.com
2024-06-03 00:27:38 Monday
登录
文章检索 我的文章 写文章
C++如何输出小数点后为0的数?
2023-07-10 21:34:59 深夜i     --     --
C++ 输出 小数点 后为0的数

在C++中,输出小数点后为0的数可以通过设置输出格式来实现。具体的方法是使用`setprecision()`函数来控制输出的精度,再使用`fixed`控制小数点位数。

首先,需要包含头文件` `,然后使用`cout`输出函数输出小数。例如:


#include <iostream>

#include <iomanip>

using namespace std;

int main() {

  double num1 = 3.14;

  double num2 = 5.0;

  double num3 = 1.0 / 3;

  cout << fixed << setprecision(0) << num1 << endl; // 输出3

  cout << fixed << setprecision(0) << num2 << endl; // 输出5

  cout << fixed << setprecision(0) << num3 << endl; // 输出0

  return 0;

}

在上面的代码中,`setprecision(0)`表示输出小数点后的零位,`fixed`表示输出定点数(即小数点后的位数)。

注意:当要输出小数位为0的数时,需要使用`fixed`关键字,否则不起作用。同时,需要注意`setprecision()`是四舍五入,如果需要向下取整可以使用`floor()`函数。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复