Python的math.gcd()函数用于计算两个整数的最大公约数(Greatest Common Divisor,GCD)。在使用该函数时,如果传入的参数不是整数或者传入的参数为负数,会引发相应的异常。
TypeError异常。例如:import mathtry: result = math.gcd(3.5, 4)except TypeError as e: print("Error:", e)输出结果:
Error: gcd() only accepts integers.当传入的参数为负数时,会引发ValueError异常。例如:import mathtry: result = math.gcd(-3, 4)except ValueError as e: print("Error:", e)输出结果:
Error: gcd() requires non-negative arguments.为了避免这些异常,可以在调用math.gcd()函数之前对输入进行检查,确保输入的参数是非负整数。


