十进制模块能处理未知值吗?

2024-05-29 04:39:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我是十进制模块的新手,我不确定十进制模块是否能够读取和处理未知值。为了使代码正常工作,我可以修改什么

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

    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'>]


Tags: 模块numberinputyourisfloatfirstdecimal
2条回答

你的意思是:

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)

请参见代码中的注释

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

相关问题 更多 >

    热门问题