c - 如何在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
**********
* *
* *
* *
* *
* *
* *
* *
* *
**********
推荐阅读
- android - 将图像添加到 PDF、Android Studio
- format - MigraDoc 格式化
- angular - 直接在浏览器中将 URL 写入定义的路由器路由时出现 404
- python - Kivy 修复“片段着色器未读取顶点着色器‘frag_color’的输出”消息
- mysql - 基于值的数据透视表和聚合
- jspdf - jsPDF fromHTML 图像(到大)和页边距底部(不工作)
- android - paddingBottom 尺寸是多少?
- selenium - 我正在尝试使用 Capybara 找到一个不可见的字段来填写,但我所做的一切似乎都不起作用
- javascript - createElement(script)/appendChild 如何调试添加的脚本?
- python - 使用绑定方法调用 PyObject_Call 段错误