Python 代码优化:实现正整数最大公约数与最小公倍数计算并处理输入错误
Your code for calculating the greatest common divisor (GCD) and least common multiple (LCM) of two numbers is mostly correct, but there are a few improvements and corrections that can be made: 1. The `gcd` function should handle cases where either `a` or `b` is zero more gracefully. 2. Using `eval` to get user input is not recommended due to security concerns. Instead, use `int` to convert the input to an integer. 3. Adding some error handling to ensure the inputs are valid positive integers. Here's the improved version of your code: ```python import math def gcd(a, b): while b != 0: a, b = b, a % b return a def lcm(a, b): return abs(a * b) // gcd(a, b) try: num1 = int(input("请输入正整数a:")) num2 = int(input("请输入正整数b:")) if num1 <= 0 or num2 <= 0: raise ValueError("输入必须是正整数。") print("最大公约数:", gcd(num1, num2)) print("最小公倍数:", lcm(num1, num2)) except ValueError as e: print("无效输入:", e) ``` ### Explanation: 1. **GCD Function**: I replaced the `math.gcd` with a custom implementation using the Euclidean algorithm, which is more educational and avoids relying on external libraries. 2. **Input Handling**: Used `int` to convert the input directly to an integer and added error handling to ensure the inputs are positive integers. 3. **Error Handling**: Added a try-except block to catch invalid inputs and provide meaningful error messages. This code will now correctly calculate the GCD and LCM of two positive integers and handle invalid inputs gracefully. ######[AI写代码神器 | 457点数解答 | 2024-11-25 18:17:48]
- Python 运行报错:urllib3 网络连接创建失败,原因及排查建议(字节豆包 | 161点数解答 | 2024-10-31 00:39:36)458
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)343
- 高考毕业晚会难题:从学生能力值求最大默契程度的Python解法(字节豆包 | 487点数解答 | 2026-01-24 13:10:18)40
- Photoshop 错误 8800 大揭秘:原因分析与实用解决方案(DeepSeek | 349点数解答 | 2025-02-28 11:19:16)569
- MaxScript 导出模型长度到 CSV 文件:代码错误排查与修正全解析 (字节豆包 | 525点数解答 | 2025-07-09 15:37:45)190
- Python 实战:学生信息列表转字典、遍历、深拷贝及数据修改全流程(GPT | 422点数解答 | 2024-10-29 15:43:54)414
- Python实战:学生成绩列表转字典,深拷贝与数据修改操作全解析(字节豆包 | 254点数解答 | 2024-10-29 16:01:39)405
- CentOS下Java进程出现futex_wait_queue_me问题的处理全流程(阿里通义 | 283点数解答 | 2023-11-20 14:51:26)459
- 替雷利珠单抗致免疫相关性糖尿病:病例报道与机制探讨,为临床用药敲响警钟( | 164点数解答 | 2024-10-11 14:52:52)264
- Python 代码优化:实现正整数最大公约数与最小公倍数计算并处理输入错误(讯飞星火 | 457点数解答 | 2024-11-25 18:17:48)388
- Python代码揭秘:巧用辗转相除法求两数最小公倍数(字节豆包 | 468点数解答 | 2025-12-21 07:31:46)34
- Python代码详解:用辗转相除法求两数最小公倍数(字节豆包 | 491点数解答 | 2025-12-21 07:32:42)33