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中查詢三個數字中最大值的完整示例:
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.") }
輸出
The values are defined as -50, 30 and 50 The third value i.e 50 is the largest number.
示例2
在這個例子中,我們將找到Kotlin中三個數字中的最大值
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中找到三個數字中的最大值:
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.
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP