Skip to content

Latest commit

 

History

History
60 lines (41 loc) · 1.56 KB

File metadata and controls

60 lines (41 loc) · 1.56 KB

Kotlin 程序:检查数字是正数还是负数

原文: https://www.programiz.com/kotlin-programming/examples/positive-negative

在此程序中,您将学习检查给定的数字是正数还是负数。 这可以通过在 Kotlin 中使用if-else语句或when表达式来完成。

要检查数字是正数还是负数,请将其与 0 进行比较。

  • 如果数字大于零,则为正数。
  • 如果数字小于零,则为负数。
  • 如果数字等于零,则为零。

示例 1:使用if else语句检查数字是正数还是负数

fun main(args: Array<String>) {

    val number = 12.3

    if (number < 0.0)
        println("$number is a negative number.")
    else if (number > 0.0)
        println("$number is a positive number.")
    else
        println("$number is 0.")
}

运行该程序时,输出为:

12.3 is a positive number.

以下是等效的 Java 代码:用于检查数字是正数还是负数的 Java 程序


上述程序中的if else语句也可以使用when表达式替换。

示例 2:使用when表达式检查数字是正数还是负数

fun main(args: Array<String>) {

    val number = -12.3

    when {
        number < 0.0 -> println("$number is a negative number.")
        number > 0.0 -> println("$number is a positive number.")
        else -> println("$number is 0.")
    }
}

运行该程序时,输出为:

-12.3 is a negative number.