c - 在 C 中制作带有星号的正方形

标签 c

我是C语言新手,请帮助我。 好吧,我正在编写一个代码来制作一个星号正方形。但我不知道如何完全制作正方形。这是我的代码:

#include<stdio.h>

int main(void){
    int n;

    for(n=1;n<5;n++){
        printf("*");
    }
    for (n=1;n<4;n++){
        printf("*\n");
    }
    for (n=1;n<=5;n++){
        printf("*");
    }
    for(n=5;n<=1;n--){
        printf("*\n");
    }

    getchar();
    return 0;
}

谢谢!! 它应该完全像

                           *****
                           *   *
                           *   *
                           *   *
                           *****

最佳答案

由于您希望创建一个星号空心方形:

考虑如何创建它。经过一番思考,你会意识到:

  1. 第一行和最后一行都是星号。
  2. 对于所有其他行,这些行的第一列和最后一列都是星号。
  3. 其他一切都是空格。

使用它,我们可以构造:

const int n = 5;

for(int i=0; i < n; i++) {
    for(int j=0; j < n; j++) {
        if (i == 0 || i == n - 1) {
            printf("*");
        }
        else if(j == 0 || j == n - 1) {
            printf("*");
        }
        else {
            printf(" ");
        }
        printf(" ");
    }
    printf("\n");
}

可以将其放入 n*m 情况的通用解决方案中:

const int ROWS = 5;
const int COLS = 5;

for(int i=0; i < ROWS; i++) {
    for(int j=0; j < COLS; j++) {
        if (i == 0 || i == ROWS - 1) {
            printf("*");
        }
        else if(j == 0 || j == COLS -1) {
            printf("*");
        }
        else {
            printf(" ");
        }
        printf(" ");
    }
    printf("\n");
}

关于c - 在 C 中制作带有星号的正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21638225/

相关文章:

c - 在C中实现由上/下箭头键触发的命令历史记录

c - 返回 scanf 并且不运行循环

c - 缓冲增长战略

c - 如何针对 linux 换行符\r\n 字符处理任何文本文件中的换行符 '\n'?

C 从文件加载文本,打印转义字符

c - 从c中的特定接口(interface)发送数据包

c++ - 函数在不应该的时候突然返回

c - while 循环在 c 中未按预期工作

c - PTY以更小的尺寸运行

ios - 我应该如何在 PinchGestureRecognizer 上保持缩放比例?