Kotlin 查找三个数字中最大值的程序

示例 1:使用 if..else 语句查找三个数中最大的数

fun main(args: Array<String>) {

    val n1 = -4.5
    val n2 = 3.9
    val n3 = 2.5

    if (n1 >= n2 && n1 >= n3)
        println("$n1 is the largest number.")
    else if (n2 >= n1 && n2 >= n3)
        println("$n2 is the largest number.")
    else
        println("$n3 is the largest number.")
}

运行程序后,输出将是

3.9 is the largest number.

在上面的程序中,三个数字 -4.53.92.5 分别存储在变量 n1n2n3 中。

然后,为了找到最大的数,使用 if else 语句检查以下条件:

  • 如果 n1 大于或等于 n2n3,则 n1 是最大的。
  • 如果 n2 大于或等于 n1n3,则 n2 是最大的。
  • 否则,n3 是最大的。

也可以使用 when 语句找到最大的数字。

以下是等效的 Java 代码:Java 查找三个数中最大数的程序


示例 2:使用 when 语句查找三个数中最大的数

fun main(args: Array<String>) {

    val n1 = -4.5
    val n2 = 3.9
    val n3 = 5.5

    when {
        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 块。

因此,两个程序中的上述条件是相同的。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战