簡體   English   中英

如何根據數字編寫階乘?

[英]How can I write a factorial based on the number?

所以我;正在嘗試編寫一個 function file(s:int, filn:str) -> 沒有寫入 n 的值。 到具有指定文件名的文件。

n. 是 n 將計算階乘的程度的數字。

例如:

file(10, 'test.out')
# test.out
3628800

到目前為止,這是我對代碼的嘗試,顯然根本不起作用,我應該改變什么?

filn = 100

def file(s:int, filn:str):
    s = open(filn)
    q = s.read()
    for i in range(1,s+1):
        return (q * i)

print(file(10, 'data'))

計算階乘值以及何時將其寫入文件。

def file(x: int, file_name: str) -> None:
    factorial = 1
    for i in range(2, x + 1):
        factorial *= i
    with open(file_name, 'w') as file:
        file.write(str(factorial))

這個 function 寫入x! file_name名稱寫入文件。

除非您堅持自己計算階乘,否則您可能還應該使用數學庫來提高效率。

將 Ratery 的答案與數學庫一起使用:

from math import factorial

def file(x: int, file_name: str) -> None:
    with open(file_name, 'w') as file:
        file.write(str(factorial(x)))

暫無
暫無

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

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