Java程式檢查數字的所有位數是否都能整除它


要檢查數字的所有位數是否都能整除它,Java程式碼如下:

示例

 線上演示

import java.io.*;
public class Demo{
   static boolean divisibility_check(int val, int digit){
      return (digit != 0 && val % digit == 0);
   }
   static boolean divide_digits(int val){
      int temp = val;
      while (temp > 0){
         int digit = val % 10;
         if ((divisibility_check(val, digit)) == false)
         return false;
         temp /= 10;
      }
      return true;
   }
   public static void main(String args[]){
      int val = 150;
      if (divide_digits(val))
      System.out.println("All the digits of the number divide the number completely.");
      else
      System.out.println("All the digits of the number are not divided by the number
      completely.");
   }
}

輸出

All the digits of the number are not divided by the number completely.

名為Demo的類包含一個名為“divisibility_check”的函式,該函式有兩個引數:數字和位數。此函式根據返回的輸出是真還是假返回布林值。它檢查數字是否不為0,以及數字除以數字的位數是否能完全整除。

另一個名為“divide_digits”的函式是一個布林函式,它以數字作為引數。此函式檢查數字中的所有位數是否都能完全整除該數字。在主函式中,定義了數字的值並使用此值呼叫該函式,如果它返回“true”,則顯示相關訊息。如果不是,則會顯示一條訊息,說明該數字不能被完全整除。

更新於:2020年7月8日

219 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.