【问题标题】:my simple calculator in python doesnt work with negative numbers我在 python 中的简单计算器不适用于负数
【发布时间】:2021-04-24 02:04:47
【问题描述】:

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

【问题讨论】:

  • 当您输入负数时会得到什么?当你寻求帮助时,这一点很重要。请阅读How to Askquestion checklist。欢迎使用 Stack Overflow!

标签: python calculator


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这就是我会做的。问题是你不能取负数的第 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)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2015-12-12
      • 2011-12-01
      • 1970-01-01
      • 2016-05-07
      相关资源
      最近更新 更多