Java
 Computer >> コンピューター >  >> プログラミング >> Java

数値が正か負かをチェックするJavaプログラム


この記事では、数値が正か負かを確認する方法を理解します。これは、指定された数値が0より大きいか小さいかを確認することで実現されます。

以下は同じのデモンストレーションです-

入力

入力が-

であると仮定します
Enter the number: -3

出力

必要な出力は-

になります
The number -30 is a negative number

アルゴリズム

Step 1 - START
Step 2 - Declare an integer values namely my_input.
Step 3 - Read the required values from the user/ define the values
Step 4 - Using an if-else condition, check my_input > 0 value.
Step 5 - If the result is true, then it’s a positive number, else it’s a negative number.
Step 6 - Display the result
Step 7 - Stop

例1

ここでは、プロンプトに基づいてユーザーが入力を入力しています。この例は、コーディンググラウンドツールでライブで試すことができます 数値が正か負かをチェックするJavaプログラム

import java.util.Scanner;
public class PositiveNegative {
   public static void main(String[] args) {
      int my_input;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the number : ");
      my_input = my_scanner.nextInt();
      if(my_input > 0)
          System.out.println("The number " +my_input + " is a positive number");
      else
         System.out.println("The number " +my_input + " is a negative number");
   }
}

出力

Required packages have been imported
A reader object has been defined
Enter the number : -30
The number -30 is a negative number

例2

ここでは、整数は事前に定義されており、その値にアクセスしてコンソールに表示されます。

public class PositiveNegative {
   public static void main(String[] args) {
      int my_input;
      my_input = -30;
      System.out.println("The number is defined as " +my_input);
      if(my_input > 0)
         System.out.println("The number " +my_input + " is a positive number");
      else
         System.out.println("The number " +my_input + " is a negative number");
   }
}

出力

The number is defined as -30
The number -30 is a negative number

  1. 数値が正、負、または0であるかどうかを確認するPythonプログラム

    数値が正、負、または0であるかどうかを確認する必要がある場合は、単純な「if」条件を使用できます。 以下は同じのデモンストレーションです- 例 my_num = 58 if my_num >= 0:    if my_num == 0:       print("The number is equal to zero")    else:       print("It is a positive number") else:   &nb

  2. 数値が正、負、奇数、偶数、ゼロかどうかをチェックするプログラム?

    数字が与えられているので、数字が偶数または奇数で正または負であることを確認する必要があります。 アルゴリズム Step 1: input number Step 2: check number is greater than equal to 0 or not. If true then positive otherwise negative and if it 0 then number is 0. Step 3: if number is divisible by 2 then it’s even otherwise its odd. サンプルコード # Python prog