![](/img/trans.png)
[英]Assignments are not expressions, and only expressions are allowed in this context kotllin error
[英]assignments are not expressions, and only expressions are allowed in this context — how to resolve this error
我試圖找到 num1 的 num2 次冪的結果:這是我的代碼 ->
fun power(num1 : Int, num2: Int): Int {
var result = 1
while (num2 != 0) {
return result *= num1
num2--
}
}
但是上面的代碼產生了以下錯誤-->
Calculator.kt:30:16: error: assignments are not expressions, and only expressions are allowed in this context
return result *= num1
^
Calculator.kt:33:5: error: a 'return' expression required in a function with a block body ('{...}')
}
^
我已經閱讀了許多文章,但無法理解。 任何幫助將不勝感激。 謝謝
表達式是計算結果為值的東西。 賦值是為變量或屬性賦值的東西。
x *= y
是x = x * y
簡寫賦值。
你不能返回一個賦值,因為它不計算為一個值。 賦值在等號的右側包含一個表達式,但作為一個整體並不代表一個表達式。
您還有其他一些語法問題。 您不能修改函數參數的值(不允許num2--
)。
邏輯也說不通。 return
立即返回一個表達式。 要修復您的代碼,您需要從num2
創建一個局部變量,並將 return 語句移到最后。
fun power(num1 : Int, num2: Int): Int {
var result = 1
var count = num2
while (count != 0) {
result *= num1
count--
}
return result
}
僅供參考,有一個稱為repeat
的函數,它比使用帶有計數器的 while 循環更簡單。 它按照您給出的次數運行括號內的代碼。
fun power(num1 : Int, num2: Int): Int {
var result = 1
repeat(num2) {
result *= num1
}
return result
}
您的函數包含多個錯誤,建議您學習 Kotlin,這里有一個參考。 Kotlin 網站有更多材料。
回到你的問題,我修改了你的函數:
fun power(num1 : Int, num2: Int): Int {
var result = 1
var num2_local = num2
while (num2_local != 0) {
result *= num1
num2_local--
}
return result
}
你的版本問題:
如果您在函數中保留本地可修改引用(var 關鍵字),那么您就實現了目標
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.