首页 > 解决方案 > 如何在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;
}

标签: cfor-loopprintfscanfspace

解决方案


完美可靠的方法(注意评论):

#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
**********
*        *
*        *
*        *
*        *
*        *
*        *
*        *
*        *
**********

推荐阅读