gpt4 book ai didi

python - decimal 模块可以处理未知值吗?

转载 作者:太空宇宙 更新时间:2023-11-04 04:09:04 25 4
gpt4 key购买 nike

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

我研究过,但是我找不到理想的答案

    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 - decimal 模块可以处理未知值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56702065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com