我正在写一个函数从数字中提取小数点。忽略异常及其语法,我正在使用2.5.2(默认Leopard版本)。我的功能还没有处理0的。我的问题是,该函数会产生一定数量的随机错误,我不明白原因。代码后我会发布错误读数。从Python中的数字中提取小数点
功能:
def extractDecimals(num):
try:
if(num > int(num)):
decimals = num - int(num)
while(decimals > int(decimals)):
print 'decimal: ' + str(decimals)
print 'int: ' + str(int(decimals))
decimals *= 10
decimals = int(decimals)
return decimals
else:
raise DecimalError(num)
except DecimalError, e:
e.printErrorMessage()
异常类:
class DecimalError(Exception):
def __init__(self, value):
self.value = value
def printErrorMessage(self):
print 'The number, ' + str(self.value) + ', is not a decimal.'
这里是误差输出WH恩我输入数字1.988:
decimal: 0.988
int: 0
decimal: 9.88
int: 9
decimal: 98.8
int: 98
decimal: 988.0
int: 987
decimal: 9880.0
int: 9879
decimal: 98800.0
int: 98799
decimal: 988000.0
int: 987999
decimal: 9880000.0
int: 9879999
decimal: 98800000.0
int: 98799999
decimal: 988000000.0
int: 987999999
decimal: 9880000000.0
int: 9879999999
decimal: 98800000000.0
int: 98799999999
decimal: 988000000000.0
int: 987999999999
decimal: 9.88e+12
int: 9879999999999
decimal: 9.88e+13
int: 98799999999999
decimal: 9.88e+14
int: 987999999999999
9879999999999998
我不知道为什么这个错误被弹出。希望你们能帮助我。
感谢所有人的帮助。正如你们所指出的那样,我可以更好地完成这个项目,但是我对结果并不感兴趣,并且对我一路上学到的东西更感兴趣。这就是为什么我不使用Python的所有内置功能的原因之一。感谢您的答案。 – dbmikus 2009-10-25 16:25:15