我写了一个短代码,输出斐波那契数列的前n个数字,其中n是传递的参数的值,每个数字都打印在新行中。 我的问题是输出不是从0开始,而是从1开始。如何在输出中也获得0?
def fibonacci(n):
fib1 = 0
fib2 = 1
for x in range(0,n):
print("%d\n" %(fib2), end = " ")
next = fib1 + fib2
fib1 = fib2
fib2 = next
这是输出,为什么第一个输入后的数字为何? output
答案 0 :(得分:0)
def fibonacci(n):
fib1 = 0
fib2 = 1
for x in range(0,n):
print("%d\n" %(fib1), end = " ")
next = fib1 + fib2
fib1 = fib2
fib2 = next
简单打印fib1
,而不是fib2
的{{1}}
如果打印了line #5
的{{1}},那么在开始时如何期望输出0
答案 1 :(得分:0)
您可以使用:
CREATE TABLE diagnosis (
dia_ref number(12) not null,
dia_type varchar2(20),
dia_date date,
dia_result varchar2(8), --Either Negative or positive.
out_pat_ID number(5),
in_pat_ID number(5),
constraint chk_diagnosis_pat_id
check ( (out_pat_id is not null and in_pat_id is null) or
(out_pat_id is null and in_pat_id is not null)
),
constraint dia_pk primary key (dia_ref),
--one of the following is going to be null when you insert rows into this table since one diagnosis can only be associated with a single patient
constraint dia_out_fk foreign key (out_pat_ID) references out_patient (out_pat_ID),
constraints dia_in_fk foreign key (in_pat_ID) references in_patient (in_pat_ID)
);
或者,您可以只切换persons
和def fibonacci(n):
fib1 = 0
fib2 = 1
for x in range(0, n):
print("%d" %(fib1))
fib1, fib2 = fib2, fib1 + fib2
的值,而不必再弄乱代码了。
答案 2 :(得分:0)
在其他示例中已提到,您可以解决您的问题..我正在分享更多的方法来实现..较短的代码
def fibonacci_fun(n):
a, b = 0, 1
for x in range(2, n):
print('%s' % a)
a, b = b, a+b
fibonacci_fun(n)
使用while循环的另一种方式
def fibonacci(n):
a, b = 0, 1
while a <= n:
print(a)
a, b = b, a+b
fibonacci(n)