KiKi实现一个简单计算器,实现两个数的“加减乘除”运算,用户从键盘输入算式“操作数1运算符操作数2”,计算并输出表达式的值,如果输入的运算符号不包括在(+、-、*、/)范围内,输出“Invalid operation!”。当运算符为除法运算,即“/”时。如果操作数2等于0.0,则输出“Wrong!Division by zero!”
数据范围:字符串长度满足 ,保证运算符是一个char类型字符。
输入一行字符串,操作数1+运算符+操作数2 (其中合法的运算符包括:+、-、*、/)。
输出为一行。
如果操作数和运算符号均合法,则输出一个表达式,操作数1运算符操作数2=运算结果,各数小数点后均保留4位,数和符号之间没有空格。
如果输入的运算符号不包括在(+、-、*、/)范围内,输出“Invalid operation!”。当运算符为除法运算,即“/”时。
如果操作数2等于0.0,则输出“Wrong!Division by zero!”。
1.0+3.0
1.0000+3.0000=4.0000
1.0;4.0
Invalid operation!
44.0/0.0
Wrong!Division by zero!
def calculator(x): for symb in x: if symb in ['+', '-', '*', '/']: a, b = map(float, x.split(symb)) if symb == '/' and b == 0: print('Wrong!Division by zero!') else: print('%.4f%s%.4f=%.4f' % (a, symb, b, eval(x))) break else: print('Invalid operation!')
while True: try: In = input() if '+' in In: s = In.split('+') num1,num2 = map(float,s) print("%.4f+%.4f=%.4f"%(num1,num2,num1+num2)) elif '-' in In: s = In.split('-') num1,num2 = map(float,s) print("%.4f-%.4f=%.4f"%(num1,num2,num1-num2)) elif '*' in In: s = In.split('*') num1,num2 = map(float,s) print("%.4f*%.4f=%.4f"%(num1,num2,num1*num2)) elif '/' in In: s = In.split('/') num1,num2 = map(float,s) if num2 == 0: print("Wrong!Division by zero!") print("%.4f/%.4f=%.4f"%(num1,num2,num1/num2)) else: print("Invalid operation!") except: break
def cal(x): if '+' in x: a,b=map(float,x.split("+")) return("%.4f+%.4f=%.4f"%(a,b,a+b)) elif '-' in x: a,b=map(float,x.split("-")) return("%.4f-%.4f=%.4f"%(a,b,a-b)) elif '*' in x: a,b=map(float,x.split("*")) return("%.4f*%.4f=%.4f"%(a,b,a*b)) elif '/' in x: a,b=map(float,x.split("/")) if b ==0: return("Wrong!Division by zero!") else: return("%.4f/%.4f=%.4f"%(a,b,a/b)) else: return ("Invalid operation!") while True: try: print(cal(input())) except: break