Skip to content

Latest commit

 

History

History
49 lines (33 loc) · 1.39 KB

File metadata and controls

49 lines (33 loc) · 1.39 KB

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

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

在该程序中,您将学习检查给定的数字是正数还是负数。 这是通过使用 Java 中的if else语句完成的。

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

public class PositiveNegative {

    public static void main(String[] args) {

        double number = 12.3;

        // true if number is less than 0
        if (number < 0.0)
            System.out.println(number + " is a negative number.");

        // true if number is greater than 0
        else if ( number > 0.0)
            System.out.println(number + " is a positive number.");

        // if both test expression is evaluated to false
        else
            System.out.println(number + " is 0.");
    }
}

运行该程序时,输出为:

12.3 is a positive number.

如果将number的值更改为负数(例如 -12.3),则输出将是:

-12.3 is a negative number.

在上面的程序中,很清楚如何通过将变量number与 0 进行比较来检查其为正还是负。

如果不确定,请按以下步骤进行:

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