如何在 Python 中乘以小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28522152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:22:34  来源:igfitidea点击:

How to Multiply Decimals in Python

pythondecimal

提问by matthewpg123

I was writing a pounds to dollars converter program. I encountered some problems multiplying the two numbers.

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

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

Can anyone tell me the code to correct this program?

谁能告诉我纠正这个程序的代码?

回答by Maddy

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

main()

If you are using input, you are inputing a string. You want to input a floating number for this questions.

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

回答by Sylvain Leroux

In Python 3 inputwill return a string. This is basically equivalent of raw_inputin Python 2. So, you need to convert that string to a number before performing any calculation. And be prepared for "bad input" (i.e: non-numeric values).

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

In addition, for monetary values, it is usually nota good idea to use floats. You should use decimalto avoid rounding errors:

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

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

All of that lead to something likethat:

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

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

Producing:

生产:

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