Python的math.gcd()
函數(shù)用于計算兩個整數(shù)的最大公約數(shù)(Greatest Common Divisor,GCD)。在使用該函數(shù)時,如果傳入的參數(shù)不是整數(shù)或者傳入的參數(shù)為負數(shù),會引發(fā)相應的異常。
TypeError
異常。例如:import math
try:
result = math.gcd(3.5, 4)
except TypeError as e:
print("Error:", e)
輸出結(jié)果:
Error: gcd() only accepts integers.
ValueError
異常。例如:import math
try:
result = math.gcd(-3, 4)
except ValueError as e:
print("Error:", e)
輸出結(jié)果:
Error: gcd() requires non-negative arguments.
為了避免這些異常,可以在調(diào)用math.gcd()
函數(shù)之前對輸入進行檢查,確保輸入的參數(shù)是非負整數(shù)。