我找到并编辑了一些代码来生成Fibonacci序列的第n个,但我的问题是在图形窗口中显示它。
from graphics import *
def main():
win = GraphWin("Sample Input", 300, 300)
win.setCoords(0,0, 299, 299) # not required, just convenient
input_prompt = Text(Point(150, 200),"Enter a positive integer")
input_prompt.setStyle('bold italic') # not required, just convenient
input_prompt.draw(win)
input_integer = Entry(Point(150, 150),5)
input_integer.setText(" ")
input_integer.draw(win)
win.getMouse()
integer_number = int(input_integer.getText()) # the very line that does the input!
running_count = 0
for x in range(1, integer_number + 1):
running_count = running_count + x
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
def fibN( k ):
k = abs( int( k ))
if k == 0:
fib = 0
elif k == 1:
fib = 1
else:
counter = 2
f0 = 0
f1 = 1
fib = f0 + f1
while counter <= k:
fib = f0 + f1
f0 = f1
f1 = fib
counter += 1
print(fib)
fib_result = "Fibonacci", "term", "of", integer_number, "is", fibN(integer_number)
prompt = Text(Point(150, 50), fib_result)
prompt.draw(win)
result_string = "The number is "+str(running_count)+"."
# Text objects require a string, not a number
result = Text(Point(150, 100), result_string)
result.draw(win)
factorial_result = "Factorial", "of",integer_number, "is", factorial(integer_number) #brackets displayed, separated factorial, of
prompt = Text(Point(150, 75), factorial_result)
prompt.draw(win)
prompt = Text(Point(150, 25),"Click to end")
prompt.draw(win)
win.getMouse()
win.close()
main()
打印它,并在窗口中显示N的斐波纳契项是“无”。它打印的数字是正确的。如何更改此项以显示打印的数字?
答案 0 :(得分:0)
你的fibN功能不会返回任何内容:
def fibN( k ):
k = abs( int( k ))
if k == 0:
fib = 0
elif k == 1:
fib = 1
else:
counter = 2
f0 = 0
f1 = 1
fib = f0 + f1
while counter <= k:
fib = f0 + f1
f0 = f1
f1 = fib
counter += 1
print(fib) #this only puts the output on the screen
要替换来电的功能输出(号码fib
),您需要return fib
:
def fibN( k ):
k = abs( int( k ))
if k == 0:
fib = 0
elif k == 1:
fib = 1
else:
counter = 2
f0 = 0
f1 = 1
fib = f0 + f1
while counter <= k:
fib = f0 + f1
f0 = f1
f1 = fib
counter += 1
return fib
然后你可以根据需要做print(fibN(something))
,但你也可以在你现在正在做的图形中使用它。