在自定义drawRect()函数中有错误还是我的错误?
问题描述:
我的drawRect()函数表现得好像有一个错误。我试图确定是否在下面有一个错误,或者,如果不是我做错了。在自定义drawRect()函数中有错误还是我的错误?
我想做一个功能,在屏幕上显示一个矩形。如果程序员输入“drawRect(3,3)”,则创建一个3乘3的矩形。然而,如果程序员输入“drawRect(3,4)”,则显示矩形的右上角,然后显示无限长的顶部。有人能帮助我吗?这里是我的代码:
#include <stdio.h>
#include <stdlib.h>
#define SIDES 0xB3
#define TOP_RIGHT 0xBF
#define BOTTOM_LEFT 0xC0
#define TOP_BOTTOM 0xC4
#define BOTTOM_RIGHT 0xD9
#define TOP_LEFT 0xDA
int heightloop;
int widthloop;
int displayrect(int height, int width)
{
printf("%c",TOP_LEFT);
for(widthloop=1;widthloop<width-2;width++)
{
printf("%c",TOP_BOTTOM);
}
printf("%c\n",TOP_RIGHT);
for(heightloop=1;heightloop<height-2;height++)
{
printf("%c",SIDES);
for(widthloop=1;widthloop<width-2;width++)
{
printf(" ");
}
printf("%c\n",SIDES);
}
printf("%c",BOTTOM_LEFT);
for(widthloop=1;widthloop<width-2;width++)
{
printf("%c",TOP_BOTTOM);
}
printf("%c",BOTTOM_RIGHT);
return(0);
}
答
在你的循环中,你应该增加widthloop
和heightloop
而不是width
和height
。另外widthloop
和heightloop
应该用0初始化。
答
循环像这样:
for(widthloop=1;widthloop<width-2;width++)
和:
会一筹莫展的时候,width <= 3
或height <= 3
。
还要注意的是widthloop
和heightloop
确实应该局部变量,虽然这不是一个错误本身,只是一个“代码味道”。
谢谢!我想我正在增加矩形的宽度,因此矩形的宽度不断增加,就像我遇到的问题一样。 – smilinggoomba