close

輸入一任意正整數,判斷是否可被5和6同時整除:


import java.util.Scanner;
public class P527 {
    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        System.out.println("請輸入任一正整數:");
        int a = scn.nextInt();
        scn.close();

         // 演算方案 A
        // 基本上和P525的練習差不多,以餘數是否為0來判斷
        // 但無須進行兩次if巢狀判斷,判斷5可否整除後再判斷6
        // 同時被5和6整除,代表該整數也能被5和6之最小公倍數整除
        // if判斷a除以30是否為0

        if (a % 30 == 0) {
            System.out.println("A:可被5和6同時整除!");
        } else {
            System.out.println("A:不可被5和6同時整除!");
        }

         // 演算方案 B
        // 一次if條件判斷,但條件須滿足2個
        // a必須能被5整除"以及"能被6整除

        if (a % 5 == 0 && a % 6 == 0) {
            System.out.println("B:可被5和6同時整除!");
        } else {
            System.out.println("B:不可被5和6同時整除!");
        }
    }
}

輸出結果:
請輸入任一正整數:
120
A:可被5和6同時整除!
B:可被5和6同時整除!

arrow
arrow

    ALVIN 發表在 痞客邦 留言(0) 人氣()