嘿,我在科特林作業。我想知道當我們輸入值時有什么方法可以知道串列中哪個值最小。
例如
var userInputList = mutableList<Boolean>()
用戶輸入數字-> 5
userInputList -> false
再次用戶輸入數字-> 2
userInputList -> false, true
再次用戶輸入數字-> 7
userInputList -> false, true, false
再次用戶輸入數字-> 1
userInputList -> false, false, false, true.
我想知道的主要事情,哪一個是最小的數字。
uj5u.com熱心網友回復:
val list = mutableListOf<Int>()
while (true) {
val i = readln().toIntOrNull() ?: break
list.add(i)
val bools = list.fold(emptyList<Boolean>()) { acc, value ->
acc (value == list.minOrNull()!!)
}
println(list)
println(bools)
}
這是嘗試顯示折疊的步驟:
Input: 5 2 7 1 3
Output: [false, false, false, true, false]
acc value to evaluate evaluated why is f ot t added?
[] 5 [] f [f] 5 is not the minimum value
[f] 2 [f] f [f,f] 2 is not the minimum value
[f,f] 7 [f,f] f [f,f,f] 7 is not the minimum value
[f,f,f] 1 [f,f,f] t [f,f,f,t] 1 is the minimum value
[f,f,f,t,f] 3 [f,f,f,t] f [f,f,f,t,f] 4 is not the minimum value
uj5u.com熱心網友回復:
您可以使用該minOrNull功能
val elements = mutableListOf<Int>()
fun main() {
while(true) {
print("Enter a number:")
elements.add(
readLine()?.toIntOrNull() ?: break
)
val smallestElement = elements.minOrNull()
println("The smallest element in the list now is $smallestElement")
}
println("Bye bye!")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/430319.html
標籤:科特林
