在C ++中没有** std :: fixed **的** std :: setprecision()**的作用是什么? [英] What is the role of **std::setprecision()** without **std::fixed** in c++?

查看:408
本文介绍了在C ++中没有** std :: fixed **的** std :: setprecision()**的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如教程 http://www.cplusplus.com/reference/iomanip/setprecision/

// setprecision example
#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision

int main () {
  double f =3.14159;
  std::cout << std::setprecision(5) << f << '\n';  // prints 3.1416 and not 3.141459 why 
  std::cout << std::setprecision(9) << f << '\n';
  std::cout << std::fixed;
  std::cout << std::setprecision(5) << f << '\n';
  std::cout << std::setprecision(9) << f << '\n';
  return 0;
}

std :: cout行<< std :: setprecision(5)不会打印5个十进制数字,但是在设置 std :: fixed 后,setprecision会按预期工作.这是为什么 ?.

The line std::cout << std::setprecision(5) does not print 5 decimal digits but after std::fixed is set, the setprecision works as expected. Why is that ?.

没有 std :: fixed std :: setprecision()的作用是什么?

推荐答案

根据 http://en.cppreference.com/w/cpp/io/ios_base/precision ,精度决定要打印多少个数字,而不是浮点后面要打印的数字:

According to http://en.cppreference.com/w/cpp/io/ios_base/precision, the precision decides how many digits are printed, not how many digits after the floating point are printed:

std::ios_base::precision

管理浮动的精度(即生成多少位数字) 点输出

Manages the precision (i.e. how many digits are generated) of floating point output

这说明了四舍五入.

是的,使用std::fixed将更改对floatfield精度的解释.根据 http://www.cplusplus.com/reference/ios/ios_base/precision/:

Yes, using std::fixed will change the interpretation of the floatfield precision. According to http://www.cplusplus.com/reference/ios/ios_base/precision/:

在固定和科学记数法中,精度字段 精确指定小数点后要显示的位数, 即使其中包括尾随的十进制零.前面的数字 在这种情况下,小数点与精度无关.

In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The digits before the decimal point are not relevant for the precision in this case.

这篇关于在C ++中没有** std :: fixed **的** std :: setprecision()**的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆