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

C语言if与if-else实现疑问:打印矩形边框时为何必须使用if-else结构

Why Your Modified If-Else Logic Breaks the Border Pattern?

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:

  1. For columns 0,1,2:
    • First if triggers (since row==0 is true), so the cell is set to *.
    • Second if checks: row==3 (false) and columns==3 (false for columns 0-2). So the else runs, overwriting the * with a space.
  2. Only for column 3:
    • First if triggers (row==0 is true), setting the cell to *.
    • Second if also triggers (columns==3 is true), re-setting the cell to * (no harm here).

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:

  1. Stick with the original chained if-else if-else structure: It’s straightforward and guarantees no accidental overwriting.
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 03:12:44