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


在本文中,我们将学习如何在Kotlin中找到三个整数中的最大值。这使用大于运算符(<)来完成。这里我们使用简单的if-else条件来比较值。

以下是相同的演示

假设我们的输入是:

-50, 30 and 50

期望输出:

The largest number is 50

算法

  • 步骤1 - 开始

  • 步骤2 - 声明三个整数:input1、input2和input3

  • 步骤3 - 定义整数

  • 步骤4 - 使用if else循环,将第一个输入与其他两个输入进行比较,以检查它是否是三个整数中最大的。如果不是,则对其他两个整数重复此步骤。

  • 步骤5 - 显示结果

  • 步骤6 - 结束

示例1

在这个例子中,我们将使用Kotlin中的if…elseif…else语句找到三个数字中的最大值。首先,声明并初始化这三个数字

val input1 = -50
val input2 = 30
val input3 = 50

然后,使用if…elseif…else查找上述三个数字中的最大值:

if (input1 >= input2 && input1 >= input3)
   println("The first value i.e $input1 is the largest number.")
else if (input2 >= input1 && input2 >= input3)
   println("The second value i.e $input2 is the largest number.")
else
   println("The third value i.e $input3 is the largest number.")

现在让我们看看在Kotlin中查找三个数字中最大值的完整示例:

Open Compiler
fun main() { val input1 = -50 val input2 = 30 val input3 = 50 println("The values are defined as $input1, $input2 and $input3") if (input1 >= input2 && input1 >= input3) println("The first value i.e $input1 is the largest number.") else if (input2 >= input1 && input2 >= input3) println("The second value i.e $input2 is the largest number.") else println("The third value i.e $input3 is the largest number.") }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

The values are defined as -50, 30 and 50
The third value i.e 50 is the largest number.

示例2

在这个例子中,我们将找到Kotlin中三个数字中的最大值

Open Compiler
fun main() { val input1 = -50 val input2 = 30 val input3 = 50 println("The values are defined as $input1, $input2 and $input3") printLargestValue(input1, input2, input3) } fun printLargestValue(input1: Int, input2: Int, input3: Int) { if (input1 >= input2 && input1 >= input3) println("The first value i.e $input1 is the largest number.") else if (input2 >= input1 && input2 >= input3) println("The second value i.e $input2 is the largest number.") else println("The third value i.e $input3 is the largest number.") }

输出

The values are defined as -50, 30 and 50
The third value i.e 50 is the largest number.

示例3

在这个例子中,我们将使用when语句在Kotlin中找到三个数字中的最大值:

Open Compiler
fun main() { val input1 = 15 val input2 = 55 val input3 = 35 println("The values are defined as $input1, $input2 and $input3") when { input1 >= input2 && input1 >= input3 -> println("$input1 is the largest number.") input2 >= input1 && input2 >= input3 -> println("$input2 is the largest number.") else -> println("$input3 is the largest number.") } }

输出

The values are defined as 15, 55 and 35
55 is the largest number.

更新于:2022年10月13日

897 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告