python中浮点乘整数时的数学错误

2024-05-19 15:04:26 发布

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

def CalculateExchange(currency2,rate):
    currencyamount1 = int(input("Enter the amount: "))
    currencyamount2 = (currencyamount1 * rate)
    print(currencyamount2,currency2)

当将程序中先前获得的汇率乘以用户输入的数字时,它不输出实际的数字,只输出以汇率形式输入的金额,例如当汇率为5,输入的金额为6时,它只输出6.6.6.6,我真的可以使用帮助,我知道这个问题看起来很微不足道,也很容易纠正,但我很难解决它。


Tags: theinput汇率ratedef数字金额amount
3条回答
currencyamount2 = float(currencyamount1 * rate)

在Python 2下,函数input对输入字符串执行eval

Python 2.7.7 (default, Jun 14 2014, 23:12:13) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x=input('Enter x: ')
Enter x: 2
>>> x
2
>>> type(x)
<type 'int'>
>>> x*5
10

还有一个浮子:

>>> x=input('Enter x: ')
Enter x: 2.2
>>> type(x)
<type 'float'>
>>> x*5
11.0

由于人们普遍认为从应用程序中的用户那里获取任意代码是不明智的,因此在Python 3中改变了这种行为。

在Python 3下,input总是返回一个字符串:

Python 3.4.1 (default, May 19 2014, 13:10:29) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x=input('Enter x: ')
Enter x: 2.
>>> type(x)
<class 'str'>

这就解释了你的结果:

>>> x*5
'2.2.2.2.2.'

如果您想在Python 3中安全地拥有类似的功能,可以在调用ast.literal_eval时包装input

>>> from ast import literal_eval
>>> x=literal_eval(input('Enter x: '))
Enter x: 2.2
>>> x
2.2
>>> type(x)
<class 'float'>

或者,只需使用int(x)float(x)将用户输入转换为所需的数据类型

避免这种错误的最简单方法是在乘法之前将int转换回float

def CalculateExchange(currency2,rate):
    currencyamount1 = int(input("Enter the amount: "))
    currencyamount2 = (float(currencyamount1) * float(rate))
    print(currencyamount2,currency2)

相关问题 更多 >