求优化:n项1+11+111+...求和C代码,解决扩展性问题
Fixing the Series Sum Code for Scalability & Simplicity
Hey there! The core issue with your current code is that you’re hardcoding each digit’s weight using clunky else if branches, which locks it into only supporting up to 5 terms. Let’s rewrite this to handle any positive integer n while making the code cleaner, more efficient, and way easier to maintain.
Key Improvements We’ll Implement:
- Dynamically generate each term in the series (no more manual digit-by-digit checks)
- Calculate the sum directly by adding each generated term (no need to break down digits)
- Match the exact output format you need:
term1 + term2 + ...followed by the total sum
Optimized Code:
// Calculate sum of series: 1 + 11 + 111 + ... + n terms #include <stdio.h> int main(void) { int n; long long sum = 0; // Use 64-bit integer to avoid overflow for larger n long long current_term = 0; printf("Input the number of terms : "); scanf("%d", &n); for (int i = 1; i <= n; i++) { current_term = current_term * 10 + 1; // Generate next term dynamically sum += current_term; // Handle output formatting to avoid leading " + " if (i == 1) { printf("%lld", current_term); } else { printf(" + %lld", current_term); } } printf("\nThe Sum is : %lld\n", sum); return 0; }
Let’s Break Down the Changes:
Dynamic Term Generation:
- The line
current_term = current_term * 10 + 1is the game-changer. It builds each term incrementally:- Iteration 1:
0 * 10 + 1 = 1 - Iteration 2:
1 * 10 + 1 = 11 - Iteration 3:
11 * 10 + 1 = 111 - This works for any n, no hardcoded branches required!
- Iteration 1:
- The line
Overflow Prevention:
- We switched to
long longforsumandcurrent_termbecause even for n=10, the sum hits 1234567900—way larger than the maximum value of a 32-bit integer (~2 billion). 64-bit integers let us handle much bigger n without errors.
- We switched to
Clean Output Formatting:
- The conditional print statement ensures we don’t add an extra " + " before the first term, perfectly matching the output style you specified.
Example Output (n=5):
1 + 11 + 111 + 1111 + 11111 The Sum is : 12345
This code is scalable, readable, and eliminates the messy conditional logic from the original version.
内容的提问来源于stack exchange,提问作者user9295826
相关产品推荐
相关产品推荐

