#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<graphics.h>
#include<conio.h>
void DDALine(int x0,int y0,int x1,int y1,int color)
{
int i;
float dx,dy,length,x,y;
if(fabs(x1-x0)>=fabs(y1-y0))
length=fabs(x1-x0);
else
length=fabs(y1-y0);
dx=(x1-x0)/length;
dy=(y1-y0)/length;
i=1;
x=x0;
y=y0;
while(i<=length)
{
putpixel(int(x+0.5),int(y+0.5),color);
x=x+dx;
y=y+dy;
i++;
}
}
void code (int x,int y,int *c)
{
//xmin&ymin is left_top
int x0min,y0min,x0max,y0max;
x0min=200;
y0min=200;
x0max=400;
y0max=300;
*c=0;
if(y<y0min)
*c=*c|0x08;
else if(y>y0max)
*c=*c|0x04;
if(x>x0max)
*c=*c|0x02;
else if(x<x0min)
*c=*c|0x01;
}
void main()
{
int x1,y1,x2,y2;
int p1x,p1y,p2x,p2y,px,py;
int xmin,ymin,xmax,ymax;
int visible=0,done=1;
int cc1,cc2,c;
int i;
int gdriver=DETECT,gmode;
initgraph(&gdriver,&gmode,"D:\\TC3\\BGI");
cleardevice();
printf("please input x1,y1 :\n");
scanf("%d,%d",&x1,&y1);
printf("please input x2,y2 :\n");
scanf("%d,%d",&x2,&y2);
DDALine(x1,y1,x2,y2,WHITE);
p1x=x1;
p1y=y1;
p2x=x2;
p2y=y2;
xmin=200;
ymin=200;
xmax=400;
ymax=300;
code (p1x,p1y,&cc1);
code (p2x,p2y,&cc2);//shi jin zhi shu
//start
do{
if((cc1==0) &&(cc2==0))
{visible=1;
done=0;}
else if((cc1|cc2)!=0)
{done=0;}
else
{
if(cc1!=0)
c=cc1;
else
c=cc2;
if((c&1000)!=0) //shang
{ py=ymin;
px=p1x+(p2x-p1x)*(ymin-p1y)/(p2y-p1y;)}
else if((c&0100)!=0)//xia
{ py=ymax;
px=p1x+(p2x-p1x)*(ymax-p1y)/(p2y-p1y;)}
else if((c&0001)!=0)//left
{ px=xmin;
py=p1y+(p2y-p1y)*(xmin-p1x)/(p2x-p1x;)}
else //right
{ px=xmax;
py=p1y+(p2y-p1y)*(xmax-p1x)/(p2x-p1x;)}
if(c==cc1)
{ p1x=px;
p1y=py;
code (p1x,p1y,&cc1);}
else
{ p2x=px;
p2y=py;
code (p2x,p2y,&cc2);}
}//end else
}while (done);
if (visible==1)
{DDALine(p1x,p1y,p2x,p2y,RED);}
//printf("%d",cc1);
//printf("%d",cc2);
}
感谢有大家的陪伴!!! E-mail:bjdcbltx@