如何在计算中避免-0.0

时间:2013-11-22 20:18:38

标签: c++ c

两个双倍值。

    double a=-324.000000
    double b= 0.000000
if(a*b<0)
{
//number is less than 0
 }
else
{
//number is greater than zero
}

它总是给出一个'小于零的数字'的输出。当我将它们相乘时,得到的结果为-0.000000。但结果应为0.000000。

3 个答案:

答案 0 :(得分:1)

This is not the result that I get。你确定问题不在其他地方吗?

你在评论中说“我试过if(a==0.0){/*but it never enters here!!*/ }。”看起来这个数字实际上并不是0。

答案 1 :(得分:0)

考虑以下代码:

#include<iostream>
int main() {
  double a=-324;
  double b= 0;
  double c = a * b;
  std::cout<<std::boolalpha
           <<"a     : "<<a<<std::endl
           <<"b     : "<<b<<std::endl
           <<"c     : "<<c<<std::endl
           <<"c < 0 : "<<(c < 0)<<std::endl
           <<"c > 0 : "<<(c > 0)<<std::endl
           <<"c == 0: "<<(c == 0)<<std::endl
      ;
}

输出:

a     : -324
b     : 0
c     : -0
c < 0 : false
c > 0 : false
c == 0: true

根据IEEE Standard for Floating Point Arithmetic(也称为IEEE 754):

  

比较应忽略零的符号(所以+0 = -0)

(引自第5.11节)

你的问题出在其他地方。

答案 2 :(得分:0)

是的,可以生成-0.0的值。它确实比较等于正0.0,因此您可以执行以下操作:

double c = a * b;
if (c == 0.0)
    c = 0.0;

我实际上在Visual Studio中使用此代码来修复格式错误。确保你彻底评论,以免人们认为你疯了。