gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
给我写一个计算器程序
- User
给我写一个计算器程序
- Assistant
下面是一个简单的计算器程序的Python实现:
while True: try: num1 = float(input("请输入第一个数字: ")) num2 = float(input("请输入第二个数字: ")) operator = input("请选择运算符 (+, -, *, /): ") if operator == "+": result = num1 + num2 elif operator == "-": result = num1 - num2 elif operator == "*": result = num1 * num2 elif operator == "/": result = num1 / num2 else: print("无效的运算符") continue print("结果:", num1, operator, num2, "=", result) break except ValueError: print("输入无效,请重新输入数字") except ZeroDivisionError: print("除数不能为零,请重新输入") except Exception as e: print("发生错误:", str(e))这个程序会先要求用户输入两个数字和一个运算符,然后根据运算符的选择进行计算,并输出结果。如果输入无效,程序会提示用户重新输入。如果发生错误(如除数为零),程序会捕捉异常并提示用户重新输入。 请注意,这个程序只支持简单的四则运算,如果你需要实现更复杂的功能,你可能需要使用更高级的数学库或者自己编写更多的代码。