原文: https://www.programiz.com/kotlin-programming/examples/largest-number-three
在该程序中,您将学习使用 Kotlin 中的if else和when语句在三个数字中找到最大的数字。
示例 1:使用if..else语句在三个数字中查找最大的
fun main(args: Array<String>) {val n1 = -4.5val n2 = 3.9val n3 = 2.5if (n1 >= n2 && n1 >= n3)println("$n1 is the largest number.")else if (n2 >= n1 && n2 >= n3)println("$n2 is the largest number.")elseprintln("$n3 is the largest number.")}
运行该程序时,输出为:
3.9 is the largest number.
在上述程序中,三个数字-4.5,3.9和2.5分别存储在变量n1,n2和n3中。
然后,为了找到最大的条件,使用if else语句检查以下条件
- 如果
n1大于或等于n2和n3,则n1最大。 - 如果
n2大于或等于n1和n3,则n2最大。 - 否则,
n3最大。
也可以使用when语句找到最大的数字。
以下是等效的 Java 代码:在三个数字中查找最大的 Java 程序
示例 2:使用when语句查找三个中最大的数字
fun main(args: Array<String>) {val n1 = -4.5val n2 = 3.9val n3 = 5.5when {n1 >= n2 && n1 >= n3 -> println("$n1 is the largest number.")n2 >= n1 && n2 >= n3 -> println("$n2 is the largest number.")else -> println("$n3 is the largest number.")}}
运行该程序时,输出为:
5.5 is the largest number.
在上面的程序中,我们使用when语句代替使用an if..else if..else块。
因此,两个程序中的上述条件相同。
