Kotlin 程序来交换两个数字
在本文中,我们将了解如何在 Kotlin 中交换两个数字。这是通过使用临时变量完成的。
以下是同样的演示
假设我们的输入是
val1 : 45 val2 : 60
所需的输出为
val1 : 60 val2 : 45
算法
步骤 1 − 开始
步骤 2 − 声明三个整数:val1、val2 和 tempVal
步骤 3 − 定义值
步骤 4 − 将 val1 分配给临时变量
步骤 5 − 将 val2 分配给 val1
步骤 6 − 将临时 tempVal 变量分配给 val2
步骤 7 − 显示这两个值
步骤 8 − 停止
示例 1
在本示例中,我们将使用临时变量来交换两个数字 −
fun main() { var val1 = 45 var val2 = 60 println("The first value is defined as: $val1") println("The second value is defined as: $val2") val tempVal = val1 val1 = val2 val2 = tempVal println("After swapping") println("The first value is = $val1") println("The second value is = $val2") }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
The first value is defined as: 45 The second value is defined as: 60 After swapping The first value is = 60 The second value is = 45
示例 2
在本示例中,我们将交换两个数字,不使用临时变量 −
fun main() { var val1 = 25 var val2 = 55 println("The first value is defined as: $val1") println("The second value is defined as: $val2") val1 = val1 + val2 val2 = val1 - val2 val1 = val1 - val2 println("After swapping") println("The first value is = $val1") println("The second value is = $val2") }
输出
The first value is defined as: 25 The second value is defined as: 55 After swapping The first value is = 55 The second value is = 25
示例 3
我们还可以使用以下代码交换两个数字
fun main() { var val1 = 20 var val2 = 10 println("The first value is defined as: $val1") println("The second value is defined as: $val2") val1 = val1 - val2 val2 = val1 + val2 val1 = val2 - val1 println("After swapping") println("The first value is = $val1") println("The second value is = $val2") }
输出
The first value is defined as: 20 The second value is defined as: 10 After swapping The first value is = 10 The second value is = 20
广告