sonar常見問題

  • Cast one of the operands of this integer division to a "double"
When arithmetic is performed on integers, the result will always be an integer. You can assign that result to a long, double, or float with automatic type conversion, but having started as an int or long, the result will likely not be what you expect.

For instance, if the result of int division is assigned to a floating-point variable, precision will have been lost before the assignment. Likewise, if the result of multiplication is assigned to a long, it may have already overflowed before the assignment.

In either case, the result will not be what was expected. Instead, at least one operand should be cast or promoted to the final type before the operation takes place.

當對整數執行算術運算時,結果將始終是整數。您可以通過自動類型轉換將該結果分配給long、double或float,但在以int或long開頭之後,結果可能不是您所期望的。

例如,如果將int除法的結果賦值給浮點變量,則在賦值之前精度將丟失。同樣,如果乘法的結果被賦值給long,則它可能在賦值之前已經溢出。

無論是哪種情況,結果都不會如預期的那樣。相反,在執行操作之前,至少應將一個操作數強制轉換或提升爲最終類型。

解決方法:比如:

(double) b/1000; 這一步是把b先轉化爲Double型 然後進行計算
因爲計算的類型中有double型 所以1000自動轉化爲double型
結果就是double型 12.345
b/1000; 這一步是long型/long型 得到的結果也是long型 就是12
然後轉化爲double型 就是12.0
  •  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章