我在 python 中的简单计算器不适用于负数

my simple calculator in python doesnt work with negative numbers

我正尝试在 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)} ")

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

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 模块。

这就是我会做的。问题是你不能取负数的 n 次方根。这将导致您需要使用 c.math 的虚数。此外,您需要小心除以 0。如果用户 a 为负数或 b 为负数,我设置了一些 if-else 条件。

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

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

print(str(a) + ' + ' + str(b) + ' is ' + str(round(a + b, 3)))
print(str(a) + ' - ' + str(b) + ' is ' + str(round(a - b, 3)))
print(str(b) + ' - ' + str(a) + ' is ' + str(round(b - a, 3)))
print(str(a) + ' * ' + str(b) + ' is ' + str(round(a * b, 3)))

if b == 0:
    print('Error! Cannot divide a by 0!')
else:
    print(str(a) + ' / ' + str(b) + ' is ' + str(round(a / b, 3)))
    
if a == 0:
    print('Error! Cannot divide b by 0!')
else:
    print(str(b) + ' / ' + str(a) + ' is ' + str(round(b / a, 3)))

if (a < 0 or b == 0):
    print('Please enter a positive number for a.')
else:
    print(str(a) + ' ** ' + str(b) + ' is ' + str(round(pow(a, b), 3)))
    print(str(a) + ' root ' + str(b) + ' is ' + str(round(pow(a, (1/float(b))), 3)))

if (b < 0 or a == 0):
    print('Please enter a positive number for b.')
else:
    print(str(b) + ' ** ' + str(a) + ' is ' + str(round(pow(b, a), 3)))
    print(str(b) + ' root ' + str(a) + ' is ' + str(round(pow(b, (1/float(a))), 3)))