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

C语言实现ln(1+x)级数求和代码结果异常,求问题排查

代码问题排查与修正

核心问题分析

  • 变量类型错误:
    你将x定义为int类型,但题目要求接收实数输入,这会导致小数输入被截断,且计算时触发整数除法(如1/2结果为0而非0.5),直接导致结果偏离预期。同时scanf用%d读取实数也会引发输入错误,应改为%lf。

  • 幂次计算逻辑错误:
    泰勒展开的第k项是x^k /k,但你的代码中每次执行x *= x,会让x的幂次变成1→2→4→8…,而非公式要求的1→2→3→4…,完全不符合项数的幂次规律。正确做法是维护一个当前项变量,每次乘以原始x来得到下一次的幂次。

  • 符号处理冗余易出错:
    用if-else判断奇偶控制加减的写法冗余,可通过维护一个符号变量,每次循环翻转符号,代码更简洁且不易出错。

修正后的代码

#include <stdio.h>

int main() {
    double x = 0.0;
    int n = 1, k = 1;
    double total_x = 0.0;
    double term;
    int sign = 1; // 符号变量:1为加,-1为减

    printf("Enter the x value for calculate ( ln(1+x) ) : ");
    scanf("%lf", &x);
    printf("Enter the n value for calculate ( ln(1+x) ) : ");
    scanf("%d", &n);

    if (n <= 0) {
        printf("Result can not be calculated\n");
        return 1;
    }

    term = x; // 初始项为x^1
    while (k <= n) {
        total_x += sign * term / k;
        sign = -sign; // 翻转符号
        term *= x; // 生成下一项的幂次x^(k+1)
        k++;
    }

    printf("Result of ln(1+x)=%.4lf\n", total_x);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 20:55:06