简体   繁体   English

Android/Kotlin 中的操作顺序

[英]Order of operations in Android/Kotlin

Could anyone explain to me why this code works:谁能向我解释为什么这段代码有效:

 if (questionList[currentIndex].answer == inputAnswer) {
        correctAnswers += 1*100/questionList.size
        percentage.text = "Правильно: $correctAnswers%"

and this one doesn't:而这个没有:

 if (questionList[currentIndex].answer == inputAnswer) {
            correctAnswers += 1/questionList.size*100
            percentage.text = "Правильно: $correctAnswers%"

When I click a button, set up with the first bit of code, everything works fine and my textView gets updated, but when I change the order of operations, nothing happens (textView.text doesn't change it's value).当我单击一个按钮并使用第一段代码进行设置时,一切正常并且我的 textView 得到更新,但是当我更改操作顺序时,没有任何反应(textView.text 不会更改它的值)。

Am I missing something?我错过了什么吗?

Thank you in advance!先感谢您!

When you do math with integers, fraction components are not preserved.当您使用整数进行数学运算时,不会保留分数分量。 Suppose the size of the question list is 10.假设问题列表的大小为 10。

In your first block of code, you have在你的第一个代码块中,你有

1 * 100 / 10

Operations are done from left to right, so after the first multiplication, you have操作是从左到右完成的,所以在第一次乘法之后,你有

100 / 10

and that resolves to 10.然后解析为 10。

Now with your second block of code you have现在有了你的第二个代码块

1 / 10 * 100

The first division with floating point numbers would be 0.1, but with integers, since the fraction is not preserved, it evaluates to 0.浮点数的第一个除法将是 0.1,但对于整数,由于不保留分数,因此计算结果为 0。

0 * 100

which resolves to 0. So it will always result in zero if the dividend is smaller than the divisor.其解析为 0。因此,如果被除数小于除数,则它总是会导致零。

If you really want to present fractional numbers, you should use floating point numbers, and if you want the result to be an Int, use roundToInt() on the result.如果你真的想显示小数,你应该使用浮点数,如果你希望结果是一个 Int,对结果使用roundToInt() If you just use toInt() , it will just drop the fraction rather than rounding to the nearest integer.如果您只使用toInt() ,它只会删除分数而不是四舍五入到最接近的整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM