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

数组首尾对应元素乘积求和代码结果异常,请求排查修正

Fixing the Incorrect Product Sum Calculation in Your C Code

Let's walk through the bugs in your code that are causing the wrong result (4206199 instead of 110 for the test array {1,2,3,4,5,6,7,8,9,10}) and fix them one by one:

1. Array Size Mismatch

You declared your array as int array[n-1];, but you're trying to store n elements in it. This creates an out-of-bounds memory access when you read the nth element during input—your array only has space for n-1 elements, so writing to array[n-1] (the nth element) corrupts adjacent memory, leading to unpredictable values later.

Fix: Change the array declaration to:

int array[n];

2. Invalid Tail Element Index

Your code uses array[n-i] to access the corresponding tail element, but array indices in C start at 0 and go up to n-1. When i=0, n-i equals n, which is way beyond the last valid index (n-1). This reads garbage data from unallocated memory, which is why your result is a random large number.

Fix: Use array[n-1 - i] to correctly target the tail element. For example, with n=10 and i=0, this gives array[9] (the 10th element), which is exactly what we need.

3. Optional: Simplify Loop Termination

Your existing if(i>(n-1-i)) { break; } logic works, but you can make the loop cleaner by adjusting the for-loop condition directly. Instead of checking for a break inside the loop, set the loop to run only while i <= (n-1)/2—this ensures we stop once we've paired all elements without extra checks.

Corrected Full Code

#include<stdio.h> 
int main() { 
    int n; 
    printf("Enter the size of array: "); 
    scanf("%d",&n); 
    int array[n]; // Fixed array size
    printf("Enter the elements of array: "); 
    for(int i=0; i<n; i++) { 
        scanf("%d",&array[i]); 
    } 
    int product = 0; 
    for(int i=0; i <= (n-1)/2; i++) { // Simplified loop condition
        int f = array[i]; 
        int l = array[n-1 - i]; // Fixed tail index
        product += (f*l); 
    } 
    printf("Result: %d", product); 
    return 0; 
}

Testing the Fixed Code

For the array {1,2,3,4,5,6,7,8,9,10}, the calculation becomes:
(1*10) + (2*9) + (3*8) + (4*7) + (5*6) = 10 + 18 + 24 + 28 + 30 = 110
Which matches the expected correct result.

内容的提问来源于stack exchange,提问作者Md Arshad Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:39:41