溫馨提示×

python的gcd函數(shù)的錯誤處理機制是什么

小樊
82
2024-09-10 15:28:47
欄目: 編程語言

Python的math.gcd()函數(shù)用于計算兩個整數(shù)的最大公約數(shù)(Greatest Common Divisor,GCD)。在使用該函數(shù)時,如果傳入的參數(shù)不是整數(shù)或者傳入的參數(shù)為負數(shù),會引發(fā)相應的異常。

  1. 當傳入的參數(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.
  1. 當傳入的參數(shù)為負數(shù)時,會引發(fā)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ù)。

0