级数1/2 -3/4 5/6…n求和程序异常求助:仅num=1正常
Hey there! Let's dive into why your code only works for num=1 and fix it up step by step.
The Core Bug: Incorrect Fraction Calculation
The biggest issue is how you're computing each term m. Let's look at your line:
m=(float)(2*n-1)/2*n;
In C, division and multiplication have the same precedence and evaluate left-to-right. That means this line is actually calculating:((2*n - 1) / 2) * n
But your series needs each term to be (2n-1)/(2n) — notice the denominator is 2n, not just 2 multiplied by n later.
For example, when n=2:
- Your code computes
(3/2)*2 = 3, then flips the sign to-3(way off from the correct-3/4 = -0.75). - The fix is to wrap the entire denominator in parentheses to force the correct order of operations:
m = (float)(2*n - 1) / (2*n);
Optional: Clean Up the Sign Logic
Your current sign logic works once the fraction is fixed, but we can make it more concise if you want. Instead of checking n%2==0 and multiplying by -1 afterward, you can compute the sign directly in the term:
m = (float)(2*n - 1) / (2*n) * (n % 2 == 1 ? 1 : -1);
This uses a ternary operator to apply a positive sign for odd n (since the first term is positive) and negative for even n, which matches your series pattern perfectly.
Full Corrected Code
Here's the updated code with the fix and optional readability tweaks:
#include<stdio.h> int main() { int n, num; float sum = 0.0; // Renamed x to sum for clarity printf("Enter number of terms:\n"); scanf("%d", &num); for(n=1; n<=num; n++) { // Calculate the term with correct fraction and sign float term = (float)(2*n - 1) / (2*n); if(n % 2 == 0) { term *= -1; } sum += term; } printf("Summation is:\n%.4f\n", sum); return 0; }
Test Cases to Verify
- For
num=1: Outputs0.5000(correct, since it's just 1/2) - For
num=2: Outputs-0.2500(1/2 - 3/4 = -0.25) - For
num=3: Outputs0.5833(1/2 - 3/4 + 5/6 ≈ 0.5 - 0.75 + 0.8333)
All these now match the expected series results!
内容的提问来源于stack exchange,提问作者Web King

