首页 > 解决方案 > 我在 python 中的简单计算器不适用于负数

问题描述

我正在尝试在 python 中编写一个非常简单的计算器。问题是当我给出正数时它工作得很好但是当我输入负数时我没有得到任何答案......我不知道为什么。如果有人可以帮助我,我将不胜感激:)。这是我的代码:

print("Hi :) This is your simple calculator")

a = float(input("please enter the first number: "))

b = float(input("please enter the second number: "))

print(f"{a}+{b} is {round((a)+(b), 3)}, {a}-{b} is {round(a-(b), 3)}, {b}-{a} is {round(b-(a), 3)}, {a}*{b} is {round(a*(b), 3)}, {a}/{b} is {round(a/(b), 3 )}, {b}/{a} is {round(b/(a), 3)}, {a} to the power of {b} is {round((a)**(b), 3)}, {b}to the power of{a} is {round((b)**(a), 3)}, {b} root of {a} is {round((a)**(1/b), 3)}, {a} root of {b} is {round((b)**(1/a), 3)} ")

标签: pythoncalculator

解决方案


这是修改后的打印语句(没有根)。这部分似乎工作。

print(f"{a}+{b} is {round((a)+(b), 3)}, {a}-{b} is {round(a-(b), 3)}, {b}-{a} is {round(b-(a), 3)}, {a}{b} is {round(a * b, 3)}, {a} to the power of {b} is {round(a ** b, 3)}, {b}to the power of{a} is {round(b ** a, 3)}")

我把根去掉是因为你会遇到负数根的问题。对于复数,请查看cmath模块。


推荐阅读