1+ import math
2+ import sys
3+
4+ class ScientificCalculator :
5+ def __init__ (self ):
6+ self .memory = 0
7+ self .history = []
8+ self .constants = {
9+ 'pi' : math .pi ,
10+ 'e' : math .e ,
11+ 'tau' : math .tau ,
12+ 'inf' : float ('inf' ),
13+ 'nan' : float ('nan' )
14+ }
15+ self .functions = {
16+ 'sin' : math .sin ,
17+ 'cos' : math .cos ,
18+ 'tan' : math .tan ,
19+ 'asin' : math .asin ,
20+ 'acos' : math .acos ,
21+ 'atan' : math .atan ,
22+ 'sinh' : math .sinh ,
23+ 'cosh' : math .cosh ,
24+ 'tanh' : math .tanh ,
25+ 'log' : math .log10 ,
26+ 'ln' : math .log ,
27+ 'log2' : math .log2 ,
28+ 'exp' : math .exp ,
29+ 'sqrt' : math .sqrt ,
30+ 'cbrt' : lambda x : x ** (1 / 3 ),
31+ 'abs' : abs ,
32+ 'floor' : math .floor ,
33+ 'ceil' : math .ceil ,
34+ 'round' : round ,
35+ 'fact' : math .factorial ,
36+ 'gamma' : math .gamma ,
37+ 'erf' : math .erf
38+ }
39+
40+ def evaluate (self , expression ):
41+ """计算表达式"""
42+ try :
43+ # 替换常量
44+ for name , value in self .constants .items ():
45+ expression = expression .replace (name , str (value ))
46+
47+ # 安全评估
48+ allowed_names = {k : v for k , v in self .functions .items ()}
49+ allowed_names .update ({
50+ 'pi' : math .pi ,
51+ 'e' : math .e ,
52+ 'tau' : math .tau ,
53+ 'inf' : float ('inf' ),
54+ 'nan' : float ('nan' )
55+ })
56+ allowed_names .update ({name : getattr (math , name ) for name in dir (math )
57+ if not name .startswith ('_' )})
58+
59+ result = eval (expression , {"__builtins__" : {}}, allowed_names )
60+
61+ # 保存到历史
62+ self .history .append ((expression , result ))
63+ if len (self .history ) > 50 :
64+ self .history .pop (0 )
65+
66+ return result
67+ except Exception as e :
68+ return f"错误: { str (e )} "
69+
70+ def show_menu (self ):
71+ print ("\n " + "=" * 60 )
72+ print (" 科学计算器 Scientific Calculator" )
73+ print ("=" * 60 )
74+ print ("支持运算: +, -, *, /, **, //, %" )
75+ print ("数学函数: sin, cos, tan, asin, acos, atan" )
76+ print (" sinh, cosh, tanh, log, ln, log2" )
77+ print (" sqrt, cbrt, exp, abs, floor, ceil" )
78+ print (" fact(阶乘), gamma, erf" )
79+ print ("常量: pi, e, tau" )
80+ print ("=" * 60 )
81+ print ("特殊命令:" )
82+ print (" m+ - 存入内存" )
83+ print (" m- - 从内存减去" )
84+ print (" mr - 读取内存" )
85+ print (" mc - 清空内存" )
86+ print (" history - 查看历史" )
87+ print (" clear/h - 清屏" )
88+ print (" constants - 查看常量" )
89+ print (" help/? - 显示帮助" )
90+ print (" q/exit - 退出" )
91+ print ("=" * 60 )
92+
93+ def show_constants (self ):
94+ print ("\n 当前常量:" )
95+ for name , value in self .constants .items ():
96+ print (f" { name } = { value } " )
97+
98+ def run (self ):
99+ print ("\n 科学计算器已启动" )
100+ print ("输入 'help' 查看帮助" )
101+
102+ while True :
103+ try :
104+ # 获取输入
105+ user_input = input ("\n >>> " ).strip ().lower ()
106+
107+ if not user_input :
108+ continue
109+
110+ # 处理命令
111+ if user_input in ['q' , 'exit' , 'quit' ]:
112+ print ("再见!" )
113+ break
114+
115+ elif user_input in ['help' , '?' ]:
116+ self .show_menu ()
117+
118+ elif user_input in ['clear' , 'h' , 'cls' ]:
119+ import os
120+ os .system ('clear' if os .name == 'posix' else 'cls' )
121+
122+ elif user_input == 'history' :
123+ if not self .history :
124+ print ("暂无历史记录" )
125+ else :
126+ print ("\n 历史记录:" )
127+ for i , (expr , result ) in enumerate (self .history [- 10 :], 1 ):
128+ print (f" { i } . { expr } = { result } " )
129+
130+ elif user_input == 'constants' :
131+ self .show_constants ()
132+
133+ elif user_input == 'm+' :
134+ try :
135+ expr = input ("输入要存入内存的表达式: " )
136+ result = self .evaluate (expr )
137+ if isinstance (result , (int , float )):
138+ self .memory += result
139+ print (f"内存 += { result } = { self .memory } " )
140+ else :
141+ print (result )
142+ except :
143+ print ("无效表达式" )
144+
145+ elif user_input == 'm-' :
146+ try :
147+ expr = input ("输入要从内存减去的表达式: " )
148+ result = self .evaluate (expr )
149+ if isinstance (result , (int , float )):
150+ self .memory -= result
151+ print (f"内存 -= { result } = { self .memory } " )
152+ else :
153+ print (result )
154+ except :
155+ print ("无效表达式" )
156+
157+ elif user_input == 'mr' :
158+ print (f"内存值: { self .memory } " )
159+
160+ elif user_input == 'mc' :
161+ self .memory = 0
162+ print ("内存已清空" )
163+
164+ else :
165+ # 计算表达式
166+ result = self .evaluate (user_input )
167+ if isinstance (result , (int , float )):
168+ # 格式化输出
169+ if isinstance (result , float ) and result .is_integer ():
170+ result = int (result )
171+ print (f"= { result } " )
172+ else :
173+ print (result )
174+
175+ except KeyboardInterrupt :
176+ print ("\n 使用 'q' 退出" )
177+ except Exception as e :
178+ print (f"错误: { e } " )
179+
180+
181+ def main ():
182+ calc = ScientificCalculator ()
183+ calc .run ()
184+
185+
186+ if __name__ == "__main__" :
187+ main ()
0 commit comments