简单计算器

265 阅读1分钟
描述
KiKi实现一个简单计算器,实现两个数的“加减乘除”运算,用户从键盘输入算式“操作数1运算符操作数2”,计算并输出表达式的值,如果输入的运算符号不包括在(+、-、*、/)范围内,输出“Invalid operation!”。当运算符为除法运算,即“/”时。如果操作数2等于0.0,则输出“Wrong!Division by zero!”
输入描述:
多组输入,一行,操作数1运算符操作数2(其中运算符号包括四种:+、-、*、/)。
输出描述:
针对每组输入,输出为一行。

如果操作数和运算符号均合法,则输出一个表达式,操作数1运算符操作数2=运算结果,各数小数点后均保留4位,数和符号之间没有空格。

如果输入的运算符号不包括在(+、-、*、/)范围内,输出“Invalid operation!”。当运算符为除法运算,即“/”时。

如果操作数2等于0.0,则输出“Wrong!Division by zero!”。

image.png


while True:
    try:
        getin=input()
        f=True
        for c in getin:
            if c not in ['0','1','2','3','4','5','6','7','8','9','.','+','-','*','/']:
                print("Invalid operation!")
                f=False
                break
        if f:
            if getin.find("+")!=-1:
                pos=getin.find("+")
                op1=float(getin[0:pos])
                op2=float(getin[pos+1:])
                print("%.4f+%.4f=%.4f"%(op1,op2,op1+op2))
            elif getin.find("-")!=-1:
                pos=getin.find("-")
                op1=float(getin[0:pos])
                op2=float(getin[pos+1:])
                print("%.4f-%.4f=%.4f"%(op1,op2,op1-op2))
            elif getin.find("*")!=-1:
                pos=getin.find("*")
                op1=float(getin[0:pos])
                op2=float(getin[pos+1:])
                print("%.4f*%.4f=%.4f"%(op1,op2,op1*op2))
            else:
                pos=getin.find("/")
                op1=float(getin[0:pos])
                op2=float(getin[pos+1:])
                if op2==0:
                    print("Wrong!Division by zero!")
                else:
                    print("%.4f/%.4f=%.4f"%(op1,op2,op1/op2))
    except:
        break