机器人
积分排行榜
Scratch
积分排行榜
Python
在线答题
积分排行榜
活跃排行榜
打字练习
Microbit
C++
在线答题
积分排行榜
活跃排行榜
网盘
积分
未登录
未登录
登录学习
作者:
张一朔
更新时间:
2025-09-06 12:46
浏览:
34次
点赞:
1次
热度:
20
def calculator(): """一个简单的命令行计算器程序,支持加、减、乘、除运算""" print("简易计算器") print("支持的操作: +, -, *, /") print("输入 'c' 清除当前计算") print("输入 'q' 退出程序") print("-" * 30) current_value = 0.0 first_input = True while True: try: # 第一次输入时的提示不同 if first_input: user_input = input("请输入第一个数字: ") first_input = False else: user_input = input(f"当前结果: {current_value},请输入操作符和数字(例如 +5 或 -3): ") # 处理退出命令 if user_input.lower() == 'q': print("感谢使用,再见!") break # 处理清除命令 if user_input.lower() == 'c': current_value = 0.0 first_input = True print("已清除,重新开始") continue # 解析第一次输入的数字 if first_input is False and current_value == 0.0: current_value = float(user_input) continue # 解析操作符和数字 if len(user_input) < 2: print("输入格式错误,请重新输入") continue operator = user_input[0] number = float(user_input[1:]) # 执行计算 if operator == '+': current_value += number elif operator == '-': current_value -= number elif operator == '*': current_value *= number elif operator == '/': if number == 0: print("错误:除数不能为零") continue current_value /= number else: print(f"不支持的操作符: {operator}") continue except ValueError: print("输入错误,请输入有效的数字") except Exception as e: print(f"发生错误: {e}") print("请重新开始") current_value = 0.0 first_input = True if __name__ == "__main__": calculator()
点赞成功
分享作品
×