You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# 存储计算历史记录
history = [ ]
# 基础运算功能
def basic_calculation ( ) :
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 == " / " :
if num2 == 0 :
print ( " 错误: 除数不能为0! " )
return
result = num1 / num2
else :
print ( " 错误:无效的运算符号! " )
return
# 记录计算历史
record = f " { num1 } { operator } { num2 } = { result : .2f } "
history . append ( record )
print ( f " 计算结果: { result : .2f } " )
except ValueError :
print ( " 输入格式错误,请输入数字! " )
# 十进制转二进制
def decimal_to_binary ( ) :
try :
decimal_num = int ( input ( " 请输入要转换的十进制整数: " ) )
if decimal_num < 0 :
print ( " 请输入非负整数! " )
return
binary_num = bin ( decimal_num ) [ 2 : ] # bin()返回值带'0b'前缀,切片去掉
record = f " 十进制 { decimal_num } 转二进制 = { binary_num } "
history . append ( record )
print ( f " 十进制 { decimal_num } 转换为二进制的结果: { binary_num } " )
except ValueError :
print ( " 输入格式错误,请输入整数! " )
# 二进制转十进制
def binary_to_decimal ( ) :
binary_str = input ( " 请输入要转换的二进制数( 仅含0和1) : " )
# 验证二进制格式
if not all ( c in " 01 " for c in binary_str ) :
print ( " 错误:输入的不是二进制数! " )
return
decimal_num = int ( binary_str , 2 )
record = f " 二进制 { binary_str } 转十进制 = { decimal_num } "
history . append ( record )
print ( f " 二进制 { binary_str } 转换为十进制的结果: { decimal_num } " )
# 查看历史记录
def show_history ( ) :
if history :
print ( " \n ===== 计算历史记录 ===== " )
for i , record in enumerate ( history , 1 ) :
print ( f " { i } . { record } " )
else :
print ( " 暂无计算历史记录! " )
# 清除历史记录
def clear_history ( ) :
global history
history = [ ]
print ( " 历史记录已清除! " )
# 主菜单
def main ( ) :
while True :
print ( " \n ===== 简易计算器 ===== " )
print ( " 1. 基础运算(+、-、*、/) " )
print ( " 2. 十进制转二进制 " )
print ( " 3. 二进制转十进制 " )
print ( " 4. 查看计算历史 " )
print ( " 5. 清除计算历史 " )
print ( " 6. 退出系统 " )
choice = input ( " 请输入您的选择( 1-6) : " )
if choice == " 1 " :
basic_calculation ( )
elif choice == " 2 " :
decimal_to_binary ( )
elif choice == " 3 " :
binary_to_decimal ( )
elif choice == " 4 " :
show_history ( )
elif choice == " 5 " :
clear_history ( )
elif choice == " 6 " :
print ( " 感谢使用,再见! " )
break
else :
print ( " 输入错误,请重新选择! " )
if __name__ == " __main__ " :
main ( )