Is it valid to compare a double with an int in java?

Deadly 提交于 2019-12-27 22:39:29

问题


Utilities.getDistance(uni, enemyuni) <= uni.getAttackRange()

Utilities.getDistance returns double and getAttackRange returns int. The above code is part of an if statement and it needs to be true. So is the comparison valid?

Thanks


回答1:


Yes, it's valid - it will promote the int to a double before performing the comparison.

See JLS section 15.20.1 (Numerical Comparison Operators) which links to JLS section 5.6.2 (Binary Numeric Promotion).

From the latter:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.

  • ...




回答2:


When performing operations (including comparisons) with two different numerical types, Java will perform an implicit widening conversion. This means that when you compare a double with an int, the int is converted to a double so that Java can then compare the values as two doubles. So the short answer is yes, comparing an int and a double is valid, with a caveat.

The problem is that that you should not compare two floating-piont values for equality using ==, <=, or >= operators because of possible errors in precision. Also, you need to be careful about the special values which a double can take: NaN, POSITIVE_INFINITY, and NEGATIVE_INFINITY. I strongly suggest you do some research and learn about these problems when comparing doubles.




回答3:


This should be fine. In floating point operation/comparisons, if one argument is floating/double then other one being int is also promoted to the same.




回答4:


yes it is absolutely valid compare int datatype and double datatype..

int i =10;
double j= 10.0;
 if (i==j)
{
System.out.println("IT IS TRUE");
}



回答5:


Yes it valid, and your code should work as expected without any glitch, but this is not the best practice, static code analyzers like SonarQube shows this as a "Major" "Bug",

Major Bug img from sonarQube

Major Bug description from sonarQube

so, the right way to do this can be,

Double.compare(val1,val2)==0 

if any parameter are not floating point variable, they will be promoted to floating point.




回答6:


It will be ok.

Java will simply return true of the numerical value is equal:

    int n = 10;
    double f = 10.0;
    System.out.println(f==n);

The code above prints true.



来源:https://stackoverflow.com/questions/13297207/is-it-valid-to-compare-a-double-with-an-int-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!