You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python计算nCr时出现TypeError:fact()需0参却传1个的解决方法

解决nCr计算代码中的TypeError错误

错误信息

ERROR! Traceback (most recent call last): File "", line 16, in File "", line 13, in nCr TypeError: fact () takes 0 positional arguments but 1 was given.

原代码

#function that calculate the factorial
 def fact ():
 mul=1
 num=input ("enter number=")
 for i in range (1, num+1):
     mul=mul*i
 print ("the factorial of the number=",mul)
 fact ()
#function that calculate nCr=
def nCr():
    n=float (input ("enter 1st number(n)="))
    r=float (input ("enter 2nd number(r)="))
    nCr=fact(n)/(fact(r)*fact(n-r))
    if n>=r:
        print("the results of the fuction nCr=",nCr)
nCr()

问题分析

  1. 参数不匹配:fact函数定义时未声明参数,但在nCr中调用fact(n)、fact(r)时传入了参数,直接触发类型错误。
  2. 函数逻辑错位:原fact函数通过input手动获取输入并打印结果,无法被nCr函数直接调用获取计算值。
  3. 数据类型错误:组合数的参数n和r应为非负整数,原代码用float接收输入会导致后续阶乘计算出错。
  4. 无效递归:原fact函数末尾调用了fact(),会触发无限递归。
  5. 逻辑顺序问题:nCr先计算再判断n>=r,会导致n<r时出现无效计算。

修正后的代码

# 计算阶乘的函数
def fact(num):
    mul = 1
    # 处理负数和0的情况:0的阶乘是1,负数无阶乘返回0
    if num < 0:
        return 0
    # 确保num是整数
    num = int(num)
    for i in range(1, num + 1):
        mul *= i
    return mul

# 计算组合数nCr的函数
def nCr():
    n = int(input("enter 1st number(n)="))
    r = int(input("enter 2nd number(r)="))
    # 先判断参数合法性
    if n >= r and r >= 0:
        result = fact(n) / (fact(r) * fact(n - r))
        print("the results of the function nCr=", result)
    else:
        print("Error: n must be >= r and r cannot be negative")

# 调用nCr函数
nCr()

关键修改点

  • 给fact函数添加参数num,使其能接收外部传入的数值进行计算
  • 移除fact内部的input和print,改为返回计算结果,让nCr可以直接使用返回值
  • 将n和r的输入类型改为int,符合组合数的参数要求
  • 调整nCr的逻辑顺序,先校验参数合法性再执行计算
  • 删除fact函数末尾的fact()调用,避免无限递归

内容的提问来源于stack exchange,提问作者Asma Onsy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 13:32:30