Skip to content

Python 202 倍數判斷

Python TQC

題目說明:

請使用選擇敘述撰寫一程式,讓使用者輸入一個正整數,然後判斷它是3或5的倍數,顯示【x is a multiple of 3.】或【x is a multiple of 5.】;若此數值同時為3與5的倍數,顯示【x is a multiple of 3 and 5.】;如此數值皆不屬於3或5的倍數,顯示【x is not a multiple of 3 or 5.】,將使用者輸入的數值代入x。

範例輸入1
55

範例輸出1

55 is a multiple of 5.

範例輸入2

36

範例輸出2

36 is a multiple of 3.

範例輸入3

92

範例輸出3

92 is not a multiple of 3 or 5.

範例輸入4

15

範例輸出4

15 is a multiple of 3 and 5.

題目解析

  1. 首先,通過 % 運算符來判斷輸入的數 x 是否能被3或5整除,即判斷是否是3或5的倍數。
  2. 如果 x 能被3整除但不能被5整除,則輸出 x is a multiple of 3.。
  3. 如果 x 能被5整除但不能被3整除,則輸出 x is a multiple of 5.。
  4. 如果 x 既不能被3整除也不能被5整除,則輸出 x is not a multiple of 3 and 5.。
  5. 最後,如果 x 既能被3整除又能被5整除,則輸出 x is a multiple of 3 and 5.。

Solution

def func(x):
    if x % 3 == 0 and x % 5 == 0:
        print(f'{x} is a multiple of 3 and 5.')
    elif x % 3 == 0:
        print(f'{x} is a multiple of 3.')
    elif x % 5 == 0:
        print(f'{x} is a multiple of 5.')
    else:
        print(f'{x} is not a multiple of 3 or 5.')

x = int(input())
func(x)

Last update : 13 novembre 2024
Created : 13 novembre 2024

Comments

Comments