簡體   English   中英

打印循環時如何執行0? 我一直在嘗試在 python 中打印出階乘。 我需要在輸出中打印 0

[英]How to execute 0 when printing out the loop? I've been trying to print out the factorial in python. I need 0 to be printed in the output

    def fact(n):
        f=1
        for num in range(1,n+1):
            if num==0:
                return 1
            else:
                f=f*num
                print(num,f) 
    n=int(input())

fact(n)
#here is my code, but the output should be 
0 0
1 1
2 2
3 6
4 24
5 120
6 720
instead of 
1 1
2 2
3 6
4 24
5 120
6 720

你能告訴我哪里出了問題,我應該在代碼中添加什么嗎?

0, 0 不能真正成為階乘的一部分,因為隨后所有數字都必須乘以 0,使它們都為零。 我想你可以先打印出來。

def fact(n):
    f=1
    print(0, 0)
    for num in range(1,n+1):
        
        f=f*num
        print(num,f) 
n=int(input())
fact(n)

理所當然的認為0! = 1 和 1! = 1,那么你已經有了序列的前兩個數字。 因此,您可以乘以num+1以避免乘以零。 然后在進行下一次乘法之前獲取輸出。

def fact(n):
    f=1
    for num in range(n+1):
        print(num,f)
        f=f*(num+1)
fact(5)
0 1
1 1
2 2
3 6
4 24
5 120

如果需要,您還可以創建查找表:

def fact(n):
    FACT=[]
    f=1
    for num in range(n+1):
        FACT += [f]
        f=f*(num+1)
    return FACT

F = fact(n)

F[0]
>>> 1

F[4]
>>> 24


  • range應該從0開始,因此range(0, n+1)或只是range(n+1)因為在您的代碼中,條件永遠不會被命中
  • 當條件被滿足時,你應該有一個printprint(0, 0)
def fact(n):
    f=1
    for num in range(0,n+1):
        if num==0:
            print(num, num) # num is just 0
        else:
            f=f*num
            print(num,f)

評論:

  • 真的需要return嗎? 它始終為1 ,獨立於n
  • 0! = 1 根據定義。 也許print(0, 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM