我最终会得到大量的票数,但我几乎已经在这个逻辑练习中挣扎了好几个小时,我会感激一些帮助。给定width
和height
,编译器应绘制一个矩形。
因此,我决定使用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");
}
}
我觉得我错过了一些东西,但这太令人困惑了。请问有人请告诉我为什么我的代码没有绘制矩形?
答案 0 :(得分:1)
您缺少应打印否 *
的部分。那么你还想象什么呢?可能是空白。
所以你应该做类似
的事情if (cond1 || cond2 || cond3 ||cond4) {
printf("*");
} else {
printf(" ");
}
答案 1 :(得分:1)
存在逻辑问题。您必须在以下边界条件下打印*
a == 0
a == height-1
b == 0
b == width-1
此外,如果您不打印边界*
,则需要打印空格[]以形成结构。
有关更多优秀做法,请查看以下代码和评论
#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.
}
答案 2 :(得分:1)
打印矩形框:
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");
}
答案 3 :(得分:1)
您的想法很好,编写的代码直观且易于阅读。 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将填充最后一个colimn。将矩形视为矩阵