如何在C中使矩形的两边相等?

问题描述

用户输入长度和高度,程序应绘制一个具有这些特征的矩形,中间是空白。问题是程序打印出的一面比另一面更长。 (注意:“ x”只是我用于绘制矩形的符号,不是变量。)

这是代码

#include <stdio.h>
#include <stdlib.h>

int main()
{
    float lenght,height,i,j;
    printf("insert lenght:\n");
    scanf("%f",&lenght);
    printf("insert height:\n");
    scanf("%f",& height);
    for (i=0; i<lenght; i++) //upper lenght
    {
        printf("x");
    }
    for (i=0; i<height; i++) //height
    {
        printf("x\n");
        for (j=0; j<lenght; j++) //space
        {
            printf(" ");
        }
        printf("x\n");
    }
    for (j=0; j<=lenght; j++) //lower lenght
    {
        printf("x");
    }
    return 0;
}

解决方法

一种完美而可靠的方法(注意注释):

#include <stdio.h>

int main(void) {
    int rows,columns;
    
    printf("Input total rows and columns: ");

    if (scanf("%d%d",&rows,&columns) != 2) {
        // If the 'rows' and/or 'columns' are entered incorrectly
        printf("Please input the values correctly!\n");
        return 1;
    }

    // Iteration till 'rows'
    for (int i = 1; i <= rows; i++) {
        // Iteration till 'columns'
        for (int j = 1; j <= columns; j++)
            // Meanwhile,if 'i' is the first iteration or last iteration relative to 'rows'
            // it will print an asterisk and similarly with 'j',otherwise,a space
            if (i == 1 || i == rows || j == 1 || j == columns)
                printf("*");
            else
                printf(" ");

        // Will go to the next line on each iteration
        printf("\n");
    }

    return 0;
}

示例测试用例:

Input total rows and columns: 5 10
**********
*        *
*        *
*        *
**********

Input total rows and columns: 10 10
**********
*        *
*        *
*        *
*        *
*        *
*        *
*        *
*        *
**********