C语言if与if-else实现疑问:打印矩形边框时为何必须使用if-else结构
Let's break down exactly what's happening here, because the difference between your original if-else if-else chain and the modified two separate if statements is all about condition exclusivity and value overwriting.
Original Code Logic (Working)
Your original inner loop uses a chained if-else if-else structure, which means each condition is checked in order, and only one block of code runs per iteration:
if (row == 0 || columns == 0){ arr[row][columns]='*'; } else if (row == Num-1 || columns == Num-1){ arr[row][columns]='*'; } else arr[row][columns] = ' ';
- For any cell that's on the top edge (row=0) or left edge (columns=0), it gets set to
*and the rest of the conditions are skipped entirely. - If that's not true, it checks if the cell is on the bottom edge (row=Num-1) or right edge (columns=Num-1)—if yes, set to
*. - If neither condition is met, it sets the cell to a space.
No overwriting happens here—each cell only gets assigned once per loop iteration.
Modified Code Logic (Broken)
In your modified code, the second if is independent, and its else only applies to that single if statement:
if (row == 0 || columns == 0){ arr[row][columns]='*'; } if (row == Num-1 || columns ==Num-1){ arr[row][columns]='*'; } else arr[row][columns] = ' ';
Let's walk through what happens to the first row (row=0) when Num=4:
- For columns 0,1,2:
- First
iftriggers (sincerow==0is true), so the cell is set to*. - Second
ifchecks:row==3(false) andcolumns==3(false for columns 0-2). So theelseruns, overwriting the*with a space.
- First
- Only for column 3:
- First
iftriggers (row==0is true), setting the cell to*. - Second
ifalso triggers (columns==3is true), re-setting the cell to*(no harm here).
- First
That's why your first row ends up as * * instead of ****—the middle cells get overwritten to spaces right after being set to *!
Fixing the Issue
You have two simple, clean options to fix this:
- Stick with the original chained
if-else if-elsestructure: It’s straightforward and guarantees no accidental overwriting. - Combine all border conditions into a single
if: This is even more concise and eliminates the problem entirely:for (int columns=0; columns<Num; columns++){ if (row == 0 || columns == 0 || row == Num-1 || columns == Num-1) { arr[row][columns] = '*'; } else { arr[row][columns] = ' '; } }
This way, any cell on any of the four borders gets set to *, and all inner cells get spaces—no conflicting assignments or overwriting to worry about.
内容的提问来源于stack exchange,提问作者Ethan Jelo Martinez

