为什么 anyValue 是双精度值时 Sonar 中的 anyValue % 1 "silly math"?

Why is anyValue % 1 "silly math" in Sonar when anyValue is a double?

SonarQube 在我的代码中提出了严重的违规行为 Silly math should not be performed。描述说

Certain math operations are just silly and should not be performed because their results are predictable.

In particular, anyValue % 1 is silly because it will always return 0.

但在我的例子中,anyValue 是双倍的。这对我有用 as intended。这是实际代码:

double v = Double.parseDouble(Utils.formatDouble(Double.valueOf(value.getValue()), accuracy.intValue()));
boolean negative = v < 0;
v = Math.abs(v);
long deg = (long) Math.floor(v);

v = (v % 1) * 60;

分析器是否假设我的变量是 int(这是他们的错误)?还是我漏掉了什么?

您可以通过将表达式更改为使用显式双常量来使表达式更加明确,例如:

(v % 1.0d) * 60

这确实是一个错误,非常感谢您的报告。

问题出在代码中:https://github.com/SonarSource/sonar-java/blob/3.9/java-checks/src/main/java/org/sonar/java/checks/ConstantMathCheck.java#L117

其中绝对没有检查 % 运算符的左操作数的类型。

我刚刚提交了以下错误来处理这个问题:https://jira.sonarsource.com/browse/SONARJAVA-1457