我需要一些帮助,尝试以以下格式打印:
00: 0
01: 1
02: 1
03: 2
04: 3
05: 5
06: 8
07: 13
08: 21
09: 34
10: 55
我的代码:
import math
import time
start_time = time.time()
golden_ratio = (1 + math.sqrt(5)) / 2
def main():
num = int(input("How many Fibonacci numbers should I print? "))
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print(format(round((val)),'3d'))
main()
答案 0 :(得分:1)
import math
import time
start_time = time.time()
golden_ratio = (1 + math.sqrt(5)) / 2
def main():
num = int(input("How many Fibonacci numbers should I print? "))
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print('{}: {:.0f}'.format(number, val))
main()
答案 1 :(得分:1)
import math
import time
start_time = time.time()
golden_ratio = (1 + math.sqrt(5)) / 2
def main():
num = int(input("How many Fibonacci numbers should I print? "))
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
print(format(number, '02d'), ': ', format(round((val)),'3d'))
main()
答案 2 :(得分:1)
bag.read_text(
f"{os.getcwd()}/foods.txt",
encoding="cp1252",
blocksize="10MB",
linedelimiter="\n\n",
)
.map_partitions(lambda x: "".join(x).split("\n\n"))
def main():
stnum = input("How many Fibonacci numbers should I print? ")
dig = len(stnum)
num = int(stnum)
for number in range(0,num+1):
val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
#print(format(round((val)),'3d'))
print(f"{number:0{dig}d}: {val:.0f}")
是斐波那契数字数量的位数:如果您要求输入100斐波那契数字,则dig
为3。我使用formatted string literals(自python 3.6起可用)来格式化输出。
dig
打印整数{number:0{dig}d}
,其中number
前导0。
dig
在点后打印没有数字的浮点数。
如果您使用的是python的旧版本,并且格式化的字符串文字不可用,请使用以下命令替换print语句:
{val:.0f}