简体   繁体   English

为什么std :: cout会打印很小的科学计数法值而不是四舍五入?

[英]Why does std::cout print REALLY small scientific notation values instead of rounding to zero?

How do I get std::cout to round a very small double value to zero, instead of printing values like: 我如何获得std :: cout将很小的double值舍入为零,而不是打印如下值:

6.94532807444049e-310

or 要么

6.95321306220521e-310

I've noticed many of these overly long scientific notations that may as well be zero seem to have e-310 我注意到许多这类过长的科学记号似乎也都为e-310,它们也可能为零

There are multiple ways to round a number. 四舍五入有多种方法。 If you wanted to the nearest whole you should just use int. 如果想要最接近的整数,则应使用int。

Another way is using header #include iomanip and using the 'setprecision(2)' to set the width. 另一种方法是使用标头#include iomanip并使用'setprecision(2)'设置宽度。

The insert operation for inserting a floating-point value into a stream produces a small result because the inserted value is small. 因为插入的值很小,所以将浮点值插入流中的插入操作产生的结果很小。 It is the job of a formatting operation to show the value, not to make decisions about what changes you want to it, such as changing a small value to zero. 格式化操作的工作是显示值,而不是决定要更改的值,例如将较小的值更改为零。

If you want small values to result in zero, you can: 如果希望较小的值导致零,则可以:

  • adjust the value before inserting it into the stream, or 在将值插入流中之前对其进行调整,或者
  • request different formatting for the value. 请求该值的其他格式。

If you want to adjust the value by converting values below some threshold to zero, you can use code such as: 如果要通过将低于某个阈值的值转换为零来调整值,则可以使用以下代码:

if (abs(x) < 1e-100) x = 100;

To change the formatting, one option is to use the fixed format optionally with a precision set using setprecision from <iomanip> : 更改格式,一种选择是使用fixed有使用精密集任选格式setprecision<iomanip>

std::cout << std::fixed << std::setprecision(8);

The latter may not offer the flexibility you want, if you want to show small numbers using scientific notation (say 10 −20 ) but not very small numbers (say 10 −200 ). 如果您想使用科学计数法表示较小的数字(例如10 -20 )而不是很小的数字(例如10 -200 ),则后者可能无法提供您想要的灵活性。 There are no formatting options to allow the use of scientific notation but to chop off small numbers below an arbitrary threshold. 没有格式设置选项允许使用科学计数法,但可以截断任意阈值以下的小数字。 For that, you must use the first option of changing the value yourself. 为此,您必须使用第一个选项自己更改值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM