在Python中如何乘法小数

2024-06-16 11:58:11 发布

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

我正在写一个英镑对美元的转换程序。我遇到了两个数字相乘的问题。

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

有人能告诉我修改这个程序的代码吗?


Tags: ofin程序numberconvertinputyour数字
2条回答
def main():
    pounds = float(input('Number of Pounds: '))
    convert = pounds * .56
    print('Your amount of British pounds in US dollars is: $', convert) 

main()

如果使用输入,则输入字符串。您想为这个问题输入一个浮点数。

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

此外,对于货币价值,通常使用浮点数是一个好主意。您应该使用^{}来避免舍入错误:

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

所有这些都会导致类似这样的事情:

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")

生产:

sh$ python3 m.py
Number of Pounds: 100
Your amount of British pounds in US dollars is: $ 56.00

sh$ python3 m.py
Number of Pounds: douze
Invalid input

相关问题 更多 >