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

C语言查找级数小于0.00005的项时x≥3运行报错如何解决

问题原因

你的代码在x≥3时报错的核心原因是阶乘计算溢出,叠加几个语法、逻辑不严谨的问题,具体如下:

  • 阶乘函数fact用int类型存储结果:32位int最大仅能存储到12!(值为479001600),当x≥3时,循环里的2*i很快会超过12,阶乘溢出后会得到非法值,导致后续除法计算异常,触发运行错误。
  • 逻辑阈值不匹配:你的需求是查找小于0.00005的项,但for循环的终止条件写的是term>0.00001,二者不一致。
  • 语法不规范:main()没有声明返回值类型,不符合C语言标准,部分严格的编译器会直接报编译错误。
  • 重复调用pow、重复计算阶乘的写法效率低,还会引入不必要的精度误差。

修复方案

我们可以把阶乘的存储类型改为范围更大的double,扩大可承载的阶乘上限,修复后的代码如下:

#include <math.h>
#include <stdio.h>

// 阶乘函数返回值改为double,扩大可存储范围
double fact(int num)
{
    double fact = 1.0;
    for(int i=1; i<=num; ++i){
        fact *= i;
    }
    return fact;
}

int main()
{
    double term=1.0, x;
    int i;

    printf("Enter the value of x: ");
    scanf("%lf",&x);

    // 终止条件改为匹配需求的0.00005
    for(i=0; term>0.00005; i++){
        term = fabs((pow(-1,i) * pow(x,2*i)) / fact(2*i));
    }

    printf("The term become smaller than 0.00005 when term %d reached\n", i);
    return 0;
}

如果想要更高的计算效率,可以去掉单独的阶乘函数,用递推公式计算每一项(后一项 = 前一项 * x² / ((2i+1)*(2i+2))),避免重复计算,优化后的版本如下:

#include <stdio.h>
#include <math.h>

int main()
{
    double x, term = 1.0;
    int i = 0;
    printf("Enter the value of x: ");
    scanf("%lf", &x);
    double x_square = x * x;
    while(term > 0.00005) {
        i++;
        term = term * x_square / ((2*i -1) * 2*i);
    }
    printf("The term become smaller than 0.00005 when term %d reached\n", i);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:36:08