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

求等比数列1+x+x²+x³+……+xⁿ和的C语言代码错误排查与修正请求

Fixing Your Series Sum Code

Let's break down what's wrong with your code and fix it step by step:

1. The Nested While Loop Breaks Iteration Logic

Your for loop is supposed to iterate through each term of the series, but the inner while(i>0) loop completely hijacks this flow:

  • When the first for iteration runs (i=1), the while loop will keep executing until i drops to 0. This means your for loop will only run once, since i is now 0 and fails the i<=n check.
  • Even worse, power gets multiplied by x multiple times in one go, which doesn't match the requirement of adding one term (x^i) per iteration.

2. Initial Setup & Missing the First Term

Your target series is 1 + x + x² + ... + xⁿ — that's n+1 terms (starting from x⁰=1 up to xⁿ). But your code:

  • Starts the for loop at i=1, skipping the x⁰=1 term (though you accidentally add it once via the initial power=1, the broken loop ruins everything after that).
  • The initial logic fails to accumulate subsequent terms correctly once the loop breaks.

Corrected Iterative Code (Easy to Understand)

This version tracks each term step-by-step with clean, predictable iteration logic:

#include<stdio.h>
int main() {
    int sum = 0, n, x, i;
    int current_term = 1; // Starts with x^0 = 1, the first term of the series
    
    printf("Enter the number x: ");
    scanf("%d", &x);
    printf("Enter the limit n (series goes up to x^n): ");
    scanf("%d", &n);
    
    // Loop through all n+1 terms (from x^0 to x^n)
    for(i = 0; i <= n; i++) {
        sum += current_term;       // Add the current term to the total sum
        current_term *= x;         // Calculate the next term by multiplying with x
    }
    
    printf("The sum is %d", sum);
    return 0;
}

Alternative: Using Geometric Series Formula (Optimized)

For larger values of n, you can skip the loop entirely using the geometric series sum formula. Just handle the edge case when x=1 (to avoid division by zero):

#include<stdio.h>
#include<math.h> // Required for the pow() function

int main() {
    int n, x;
    double sum; // Use double to avoid integer overflow for large n or x values
    
    printf("Enter the number x: ");
    scanf("%d", &x);
    printf("Enter the limit n (series goes up to x^n): ");
    scanf("%d", &n);
    
    if(x == 1) {
        // When x=1, every term is 1 — sum is just the count of terms (n+1)
        sum = n + 1;
    } else {
        // Geometric series formula: sum = (x^(n+1) - 1) / (x - 1)
        sum = (pow(x, n + 1) - 1) / (x - 1);
    }
    
    printf("The sum is %.0f", sum); // %.0f prints as integer if the result is whole number
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 10:47:34