下面的代碼用于計算考試結果。5個主題名稱和5個從這些受試者接受點由在空的用戶所記錄的陣列創建的。
我已經解決了這里的一切。但我想在"cycle"之后添加"th" "st" "rd" "nd "。寫著“請輸入課程”和“請輸入要點”
例如: “請輸入第一點”
但是用我的代碼我可以: “請輸入1點”
我試圖用“When”條件執行這個程序,但我不能,因為回圈引數“cycle”不支持last()函式
例如:
when (cycle.last()) {
1 -> "st"
2 -> "nd"
}
如果在11st、531st、22nd、232nd等作業,它會給我一個結果。這就是我想要的
fun main() {
var subject = Array<String>(5){""}
var point = Array<Int>(5){0}
for (cycle in 0 until subject.count()) {
println("Please type ${cycle 1} lesson")
var typeLesson = readLine()!!.toString()
subject[cycle] = typeLesson
println("Please type ${cycle 1} point")
var typePoint = readLine()!!.toInt()
point[cycle] = typePoint
}
var sum = 0
for (cycle in 0 until point.count()) {
println("${subject[cycle]} : ${point[cycle]}")
sum = sum point[cycle]/point.count()
}
println("Average point: $sum")
}
uj5u.com熱心網友回復:
您可以將數字除以 10,然后使用 得到余數%。那是最后一個數字。
fun Int.withOrdinalSuffix(): String =
when (this % 10) {
1 -> "${this}st"
2 -> "${this}nd"
3 -> "${this}rd"
else -> "${this}th"
}
用法:
println("Please type ${(cycle 1).withOrdinalSuffix()} lesson")
請注意,在英語中,11、12、13 帶有后綴“th”,因此您可能需要這樣做:
fun Int.withOrdinalSuffix(): String =
if ((this % 100) in (11..13)) { // check last *two* digits first
"${this}th"
} else {
when (this % 10) {
1 -> "${this}st"
2 -> "${this}nd"
3 -> "${this}rd"
else -> "${this}th"
}
}
反而。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/402088.html
