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

C语言矩形绘制程序输出不符:原因排查与修复咨询

矩形绘制程序的错误分析与修复

问题描述

需要编写程序接受两个整数h和w,绘制满足以下规格的矩形:

  • 矩形高度为h,宽度为w;
  • h代表矩形的行数;
  • w为每行最大字符数,首行和末行各有w个可见字符;
  • 中间行仅行首和行尾有可见字符;
  • 可见字符为*或#,行间交替使用,首行用*,次行用#,依次循环。

现有代码:

#include <stdio.h>

void draw_rectangle(int h, int w) {
    for (int i = 0; i < h; i++) {
        if (i == 0 || i == h - 1) {  // first and last rows
            for (int j = 0; j < w; j++) {
                printf("*");
            }
        } else {  // rows in between
            if (i % 2 == 0) {
                printf("#");
                for (int j = 0; j < w - 2; j++) {
                    printf(" ");
                }
                printf("#");
            } else {
                printf("*");
                for (int j = 0; j < w - 2; j++) {
                    printf(" ");
                }
                printf("*");
            }
        }
        printf("\n");
    }
}

int main() {
    draw_rectangle(5, 10);
    return 0;
}

预期输出

Run1
5 10
**********
#      #
*      *
#      #
**********
Run2
7 4
****
#  #      
*  *
#  #
*  *
#  #
****
Run3
8 2
**
##
**
##
**
##
**
##
Run4
6 6
******
#   #
*   *
#   #
*   *
######

当前输出

Run1
5 10
**********
*        *
#        #
*        *
**********
Run2
7 4
****
*  *
#  #
*  *
#  #
*  *
****
Run3
8 2
**
**
##
**
##
**
##
**
Run4
6 6
******
*    *
#    #
*    *
#    #
******

错误原因

  1. 中间行字符逻辑颠倒:需求要求首行(i=0)用*,次行(i=1)用#交替,但现有代码中中间行i为奇数时输出*,偶数时输出#,完全和需求相反。
  2. 末行字符固定化:需求要求所有行(包括末行)按规则交替字符,但现有代码将首行和末行固定为*,导致末行在需要输出#的场景(如Run4)不符合预期。

修复方案

修复后的代码

#include <stdio.h>

void draw_rectangle(int h, int w) {
    for (int i = 0; i < h; i++) {
        // 根据行索引奇偶性确定当前行使用的字符
        char current_char = (i % 2 == 0) ? '*' : '#';
        if (i == 0 || i == h - 1) {  // 首行和末行
            for (int j = 0; j < w; j++) {
                printf("%c", current_char);
            }
        } else {  // 中间行
            printf("%c", current_char);
            for (int j = 0; j < w - 2; j++) {
                printf(" ");
            }
            printf("%c", current_char);
        }
        printf("\n");
    }
}

int main() {
    // 测试所有用例
    draw_rectangle(5, 10);
    printf("\n");
    draw_rectangle(7, 4);
    printf("\n");
    draw_rectangle(8, 2);
    printf("\n");
    draw_rectangle(6, 6);
    return 0;
}

修复说明

  1. 新增current_char变量,根据当前行索引i的奇偶性统一决定字符:i为偶数时用*,奇数时用#,完全贴合交替规则。
  2. 首行和末行不再固定输出*,而是使用current_char,保证末行字符符合交替要求。
  3. 中间行直接复用current_char作为首尾字符,简化逻辑的同时修正了之前的颠倒问题。

内容的提问来源于stack exchange,提问作者AFNAN ALHAAJ MOHAMMED

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:47:10