简体   繁体   English

避免输出为负零的最佳方法是什么?

[英]what is the best way to avoid negative zero in output?

As in this question is said, there is some differences between negative and positive zero in floating point numbers. 就像在这个问题中所说的那样,浮点数的负零和正零之间存在一些差异。 I know it's because of some important reasons. 我知道是因为一些重要原因。 what I want to know is a short code to avoid negative zero in output. 我想知道的是一个简短的代码,可避免输出为负零。

for example in the following code: 例如下面的代码:

cout << fixed << setprecision(3);
cout << (-0.0001) << endl;

"-0.000" is printed. 打印“ -0.000”。 but I want "0.000". 但我要“ 0.000”。

Note all other negative numbers (eg -0.001) should still be printed with the minus sign preceding them, so simply * -1 will not work. 请注意,所有其他负数(例如-0.001)仍应在其前面加上减号,因此* -1将不起作用。

尝试根据您的精度。

cout << ((abs(ans) < 0.0005)? 0.000: ans) << endl;

怎么样:

cout << (value == 0.0 ? abs(value) : value)  << endl;

If you care about arbitrary precision, as opposed to just a fixed one at 3, you'll need a small bit of work. 如果您关心任意精度,而不是仅仅固定为3,那么您将需要做一些工作。 Basically, you'll have to do a pre-check before the cout to see if the number will get formatted in a way you don't like. 基本上,您必须在提示之前进行预检查,以查看数字是否会以您不喜欢的方式进行格式化。

You need to find the order of magnitude of the number to see if it the imprecise digits will be lost, leaving only the sign bit. 您需要找到数字的数量级,以查看不精确的数字是否会丢失,仅保留符号位。

You can do this using the base 10 logarithm of the absolute value of the number. 您可以使用数字绝对值的以10为底的对数进行此操作。 If negative of result is greater than the precision you have set, the number will show in a way you don't want. 如果结果的负数大于您设置的精度,则数字将以您不希望的方式显示。

log10 of 0.0001 is -4. 0.0001的log10为-4。

negative of (-4) is 4. (-4)的负数是4。

4 > 3 (the arbitrary precision) Thus the value will show up unhappily. 4> 3(任意精度)因此,该值将无法显示。

In very bad pseudocode: 用非常糟糕的伪代码:

float iHateNegativeZeros(float theFloat, int precision)
{
   if((theFloat < 0.0f) &&
      (-log10(abs(theFloat)) > precision))
   {
     return -theFloat;
   }
   else
   {  
     return theFloat;
   }
}

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

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