数组首尾对应元素乘积求和代码结果异常,请求排查修正
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

