如何在Python中乘以小数

问题描述 投票:6回答:2

我正在编写磅到美元的转换器程序。我在将两个数字相乘时遇到了一些问题。

pounds = input('Number of Pounds: ')
convert = pounds * .56
print('Your amount of British pounds in US dollars is: $', convert)

有人可以告诉我纠正该程序的代码吗?

python decimal
2个回答
13
投票

在Python 3中,input将返回一个字符串。这基本上等同于Python 2中的input。因此,在执行任何计算之前,您需要将该字符串转换为数字。并为“错误输入”做好准备(即:非数字值)。

此外,对于货币值,使用浮点数通常是[[not一个好主意。您应该使用raw_input以避免舍入错误:

decimal
所有这些都会导致

like

那件事:decimal
生产中:

>>> 100*.56 56.00000000000001 >>> Decimal('100')*Decimal('.56') Decimal('56.00')


1
投票
import decimal try: pounds = decimal.Decimal(input('Number of Pounds: ')) convert = pounds * decimal.Decimal('.56') print('Your amount of British pounds in US dollars is: $', convert) except decimal.InvalidOperation: print("Invalid input")
如果使用输入,则输入字符串。您要为此问题输入一个浮点数。

0
投票
f Python很棒,伙计,我是香蕉,你是香蕉,我们都是香蕉。
© www.soinside.com 2019 - 2024. All rights reserved.