-1
我無法解決這個問題。我閱讀了同樣的錯誤的一些答案,但他們的解決方案不起作用。我沒有想法。爲什麼發生錯誤?錯誤是:NameError:name'self'未定義此名稱錯誤的其他解決方案不適用於我的代碼
謝謝。
class irNum:
def __innit__(self):
pass
def approx(irNum, digitsNum, digitsDivider, cycles):
self.approximate(irNum, digitsNum, digitsDivider, cycles)
def approximate(self):
divider = 2
bestDecimalPlaces = None
stage = 0
for i in range(0, cycles):
for stage in range(0,2):
if divider <= int("9" * digitsDivider):
if stage == 0:
num = int(round(divider * irNum, 0))
elif stage == 1:
num = (int(round(divider * irNum, 0))) - 1
elif stage == 2:
num = int(round(divider * irNum, 0)) + 1
else:
raise ValueError
if num <= int("9" * digitsNum):
approx = num/divider
difference = irNum - approx
else:
break
sIrNum = str(irNum)
sApprox = str(approx)
if len(sIrNum) >= len(sApprox):
smallest = sApprox
else:
smallest = sIrNum
decimalPlaces = 0
go = False
passed = True
a = 0
while a < len(smallest):
if go == False:
if sIrNum[a] != sApprox[a]:
passed = False
if sIrNum[a] == ".":
go = True
a += 1
if passed == False:
break
if go == True:
if sIrNum[a] == sApprox[a]:
decimalPlaces += 1
else:
break
a += 1
if bestDecimalPlaces == None:
checksOut = True
elif decimalPlaces > bestDecimalPlaces:
checksOut = True
else:
checksOut = False
if checksOut == True:
bestDecimalPlaces = decimalPlaces
bestNum = num
bestDivider = divider
bestDifference = difference
bestApprox = approx
if stage > 2:
raise ValueError
else:
stage += 1
divider += 1
return [bestNum, bestDivider, bestDecimalPlaces, bestDifference, bestApprox]
pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679
piApprox = irNum.approx(pi, 2, 2, 10 ** 3)
print(piApprox)
修復init定義中的拼寫錯誤。它應該是'def __init__'而不是'def __innit__' – putonspectacles
第二次添加堆棧跟蹤,我們想知道錯誤發生的位置 – putonspectacles