首頁  >  文章  >  Java  >  Java程序,用來檢查一個數字是否可以被5整除

Java程序,用來檢查一個數字是否可以被5整除

PHPz
PHPz轉載
2023-09-13 21:01:021515瀏覽

Java程序,用來檢查一個數字是否可以被5整除

在數學中,5 的整除規則規定,如果數字以 0 或 5 結尾,則它可以被 5 整除。還有另一種方法來確定 5 的整除規則,如果餘數為 0,則傳回該數字能被 5 整除。 mod(%)運算子通常在程式設計中用於整除。

讓我們舉個例子。

  • 給定的數字是 525,數字以 5 結尾,並且可以被 5 整除。

  • 給定的數字是 7050,數字以 0 結尾,並且可以被 5 整除。

  • 給定的數字是 678,數字不以 0 和 5 結尾,也不能被 5 整除。

在本文中,我們將解決該數字是否能被 5 整除的問題。

演算法

以下步驟是

  • 我們將使用 java.util.* 套件來取得原始資料類型的使用者輸入。

  • 從主類別開始,初始化整數變數來儲存輸入的整數。

  • 然後使用 mod(%) 運算子將整數變數除以 5。

  • 最後,列印結果。

範例 1

在這個程式中,我們將使用 if-else 語句來檢查數字是否能被 5 整除。

import java.util.*;
public class Check_Divisiblity_of_five {
   public static void main(String[] args) {
      int number =590;
      if (number % 5 == 0)
         System.out.println(number+ "\tis the number is divisible by 5");
      else
         System.out.println(number+ "\tThe number is not divisible by 5");
   }
}

輸出

590 is the number is divisible by 5

範例 2

在此程式中,我們將取得一個輸入變量,並使用「!=」運算子在 if 語句的條件下檢查它。如果帶有 mod(%) 運算子的整數變數不等於 0,則會導致該數字能被 5 整除。

import java.util.*;
public class Check_Divisible_five {
   public static void main(String[] args) {   
      int n=109;
      if(n % 5 != 0) {
         System.out.println(n+"\t is the number not divisible by 5");
      } else {
         System.out.println(n+"\t is the number divisible by 5");
      }
   }
}

輸出

109 is the number not divisible by 5

範例 3

在這個程式中,我們設定了50-100之間的數字範圍,並檢查該數字是否能被5整除。

import java.util.Scanner;
public class Divisible_by_five {
   public static void main(String []args) {
      for(int n = 50; n <= 100; n++){
         if(n % 5 == 0) {
            System.out.println("The number is divisible by 5 :\t"+ n);
         }
      }
   }
}

輸出

The number is divisible by 5 :	50
The number is divisible by 5 :	55
The number is divisible by 5 :	60
The number is divisible by 5 :	65
The number is divisible by 5 :	70
The number is divisible by 5 :	75
The number is divisible by 5 :	80
The number is divisible by 5 :	85
The number is divisible by 5 :	90
The number is divisible by 5 :	95
The number is divisible by 5 :	100

結論

我們探索了與 5 整除相關的所有三個範例。然後使用 mod(%) 運算子檢查整除規則的條件。一旦數字可以整除,它就會印出結果,否則不會。參考這個程式我們也能知道其他數的整除規則。

以上是Java程序,用來檢查一個數字是否可以被5整除的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除