我是十进制模块的新手,我不确定十进制模块是否可以读取和处理未知值。我需要更改哪些代码才能使其正常工作?

我对此进行了研究,但是找不到理想的答案

    from decimal import Decimal

    def Addition(x,y):
        sum=Decimal('x')+Decimal('y')
        print("The sum of {0} and {1} is {2}".format(x, y,sum))

    x=float(input("Enter your first  number: "))
    print("Your first number is="+str(x))
    y=float(input("Enter your second  number: "))
    print("Your second number is="+str(y))

    Addition(x,y)



我期望将x和y相加,但是输出是的无效操作
[<class 'decimal.ConversionSyntax'>]

最佳答案

查看代码中的注释。

from decimal import Decimal

def Addition(x,y):
    sum=x+y   #You don't need quotes around x and y
    print("The sum of {0} and {1} is {2}".format(x, y,sum))

x=Decimal(input("Enter your first  number: "))
print("Your first number is {}".format(x)) #No need to convert to string
y=Decimal(input("Enter your second  number: "))
print("Your second number is {}".format(y)) #No need to convert to string

Addition(x,y)


输出:

Enter your first  number: 5.789
Your first number is 5.789
Enter your second  number: 5.34566
Your second number is 5.34566
The sum of 5.789 and 5.34566 is 11.13466

关于python - 十进制模块可以处理未知值吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56702065/

10-13 08:19