C语言向量左移后右移功能异常,请求错误排查
Fixing Your Right Shift Logic in C Code
Hey Giada, I spotted the exact issue causing your right shift to output incorrect results—let's break it down step by step:
The Critical Bug: Unwanted Semicolon
Look at your right shift loop:
for (i=N-1; i>0; i--); { vet[i]=vet[i-1]; }
That semicolon ; right after the for loop declaration is a silent killer! It tells the compiler that the loop has an empty body, so the code block { vet[i]=vet[i-1]; } never runs as part of the loop. Instead, it just executes once (after the loop finishes doing nothing), which completely breaks the shift logic.
The Second (Minor) Check: Correcting the Flow
Once you remove that semicolon, the loop will work as intended, but let's confirm what it does:
- Starting from the last element (
i=N-1) and moving left to the first index (i>0), each element gets replaced by the one before it. - After the loop finishes, setting
vet[0] = 0correctly puts the zero at the start, turning2 3 4 0into0 2 3 4as you want.
Corrected Right Shift Code
Here's the fixed section of your code:
//SHIFT TO THE RIGHT// // 2 3 4 0 -> 0 2 3 4// for (i=N-1; i>0; i--) { // Removed the extra semicolon here vet[i]=vet[i-1]; } vet[0]=0;
Test Case Verification
Let's say you input 4 elements: 1 2 3 4
- Left shift gives:
2 3 4 0 - Fixed right shift will output:
0 2 3 4(exactly what you expected!)
内容的提问来源于stack exchange,提问作者Giada
相关产品推荐
相关产品推荐

