我写了这段代码。此代码处理dx和dy大于0的情况。但是,当其中一个小于0时,该怎么办。该算法说,m应该被视为绝对的,x和y应该递减。但是如何在第二个for循环中递减i(x)呢?
#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <graphics.h>
void illuminate (int x, int y, int col)
{
putpixel(x+320,240-y,col);
}
void main (void)
{
int i,x1,y1,x2,y2,j;
float dx,dy,m,e;
int gdriver=DETECT,gmode;
initgraph(&gdriver,&gmode, "C:\\TurboC3\\BGI");
printf("\nEnter the coordinates of initial point\n");
scanf("%d%d",&x1,&y1);
printf("\nEnter the coordinates of final point\n");
scanf("%d%d",&x2,&y2);
dx = x2 - x1;
dy = y2 - y1;
m = abs(dy)/abs(dx);
j = y1;
e = m - 1;
line(320,0,320,480);
line(0,240,640,240);
if ( dx >= 0 && dy >= 0 )
{
for (i=x1;i<x2-1;i++)
{
illuminate(i,j,4);
if ( e>= 0 )
{
j = j+1;
e = e-1.0;
}
e = e+m;
}
}
else
{
for (i=x1;i<x2-1;i++)
{
illuminate(i,j,4);
if (e>=0)
{
j = j-1;
e = e-1.0;
}
e = e+m;
}
}
getch();
}发布于 2014-04-11 18:58:22
处理这种情况的一种简单方法是在某个容器中“绘制”相对于x轴的线的镜像,然后再次镜像它。你实际上并不需要这样做,但这种思维方式可能会帮助你找出应该把否定放在哪里。当dx为正或负时,代码非常相似,只有几个符号不同。
https://stackoverflow.com/questions/23010065
复制相似问题