我正在研究計算器專案,但是當我嘗試使用兩種類似的方法來比較 double 和 int 數字時,我得到了不同的結果。所以我的問題是為什么這些比較方法的作業方式不同?
//some code that parse the string
//...
//code of calculating:
fun calculateIn(queueNumbers: Queue<Double>, queueActions: Queue<Char>) {
var action: Char
var result = queueNumbers.poll()
var operand: Double
while (!queueNumbers.isEmpty()) {
operand = queueNumbers.poll()
action = queueActions.poll()
when (action) {
'-' -> result -= operand
' ' -> result = operand
'*' -> result *= operand
'/' -> result /= operand
'%' -> result = result % operand * -1.0
}
}
var pointNum = 8.3
println("pointNum = " pointNum)
println(if(pointNum.compareTo(pointNum.toInt()) == 0) pointNum.toInt() else pointNum)
println("result = " result)
println(if(result.compareTo(result.toInt()) == 0) result.toInt() else result)
}
代碼結果:
"10.3 -2" //input String
[10.3, -2.0] //queueNumbers
[ ]//queueActions
pointNum = 8.3
8.3
result = 8.3
8
我認為這很奇怪,因為如果我運行類似的代碼,我會得到正確的結果:
var pointNum = 8.3
println(if(pointNum.compareTo(pointNum.toInt()) == 0) pointNum.toInt() else pointNum)
所以有這段代碼的結果:
8.3
GitHub 上的完整代碼:
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/461757.html
標籤:科特林
上一篇:在SpringAuthorizationServer(0.2.3 )中支持并發全堆疊MVC(session)認證以及無狀態JWT認證
下一篇:從finally塊回傳
