如何在 C 中绘制一个给定宽度和高度的空矩形?

How do I draw an empty rectangle given its width and height in C?

我最终会得到大量的反对票,但我确实已经为这个逻辑练习苦苦挣扎了几个小时,我希望能得到一些帮助。给定 widthheight,编译器应该绘制一个矩形。

因此我决定使用 for loops,这看起来是完成这项工作的最聪明的方法。

这是我一直在使用的代码:

#include <stdio.h>

main()

{

int width, height, b, a;

  printf("Please insert the value of the width.\n");
  scanf("%d", & width);

  printf("Please insert the value of the height.\n");
  scanf("%d", & height);

for (a = 0; a != height; a++) {

    // fill the width
    for (b = 0; b != width; b++ ) {

        if (a == 0) {
            printf("*");}

        else if (a == width-1) {
            printf("*");
        }

        else if (b == height-1) {
            printf("*");
        }

        else if (b == 0) {
            printf("*");
        }

        else {
            printf(" ");
        }}

    printf("\n");
   }
}

我觉得我错过了什么,但这太令人困惑了。有人可以告诉我为什么我的代码不绘制矩形吗?

您遗漏了应该打印 no * 的部分。那你还想打印什么?可能是空白。

所以你应该这样做

if (cond1 || cond2 || cond3 ||cond4) {
    printf("*");
} else {
    printf(" ");
}

逻辑有问题。您必须在以下 边界 条件

下打印 *
  • a == 0
  • a == height-1
  • b == 0
  • b == width-1

此外,当你不打印边界 * 时,你需要打印 space [</code>] 来制作结构形式。</p> <p>更多好的做法,请查看下面的代码和评论</p> <pre><code>#include <stdio.h> int main() //put proper signature { int width = 0, height = 0, b = 0, a = 0; // initalize local variables printf("Please insert the value of the width.\n"); scanf("%d", & width); printf("Please insert the value of the height.\n"); scanf("%d", & height); for (a = 0; a != height; a++) { // fill the width for (b = 0; b != width; b++ ) { if ((a == 0) || (a == height-1) || (b == width-1) || (b == 0)){ // put all * printing condition in one place //also, conditions, (a == height-1) and (b == width-1) to be used printf("*"); } else // if not to print *, print space printf(" "); } printf("\n"); } return 0; // add a return statement. }

要打印矩形框:

for (a = 0; a != height; a++) {

    // fill the width
    for (b = 0; b != width; b++ ) {

        if (a == 0 || a== height-1 ) {
            printf("*");
       }else{
            if(b == 0 || b == width-1){
                printf("*");
            }else{
                printf(" ");
            }
       }
    }

    // ok, the line has been filled, new line
    printf("\n");
}

你的idea不错,写的代码直观易读。 Mabye 下次多注意 if 语句,一切都会好起来的 :) for (a = 0; a != height; a++) {

// fill the width
for (b = 0; b != width; b++ ) {

    if (a == 0) {
        printf("*");
    }
    else if (a == height-1) {
        printf("*");
    }
    else if (b == width-1) {
        printf("*");
    }

变量a等于height-1表示最后一行用(*)填充,width-1填充最后一列。把你的矩形想象成一个矩阵