📄 4.7.2.c
字号:
/*4.7.2、中点分割算法 */
#include <math.h>
#include"stdio.h"
#include "Conio.h"
#include "graphics.h"
void initgr(void) /* BGI初始化 */
{ int gd=DETECT, gm=0;
registerbgidriver(EGAVGA_driver);
initgraph(&gd, &gm, "");
}
int encode(int x,int y,int xl,int xr,int yb,int yt)
{int c=0;
if (x<xl) c=c|1;
else if (x>xr) c=c|2;
if (y<yb) c=c|4;
else if (y>yt) c=c|8;
return c;
}
struct point
{int x;
int y;};
struct point *edgepoint(int x1,int y1,int x2,int y2,int xl,int xr,int yb,int yt)
{struct point *pt;
int code1,code2,code;
int xx,yy;
long d,d1,d2;
pt=(struct point *)malloc(sizeof(struct point));
code1=encode(x1,y1,xl,xr,yb,yt);
code2=encode(x2,y2,xl,xr,yb,yt);
if (code1==0)/*(x1,y1)在裁剪窗口内,返回该点*/
{xx=x1; yy=y1;
pt->x=xx; pt->y=yy;
return pt;
}
if ((code1&code2)!=0) return NULL;
do{
xx=(x1+x2)/2;
yy=(y1+y2)/2;
code=encode(xx,yy,xl,xr,yb,yt);
d1=(yy-y1)*(yy-y1);
d2=(xx-x1)*(xx-x1);
d=sqrt(d1+d2);
pt->x=xx;pt->y=yy;
if((code&code1)!=0)
{x1=xx;y1=yy;
}
else{x2=xx;
y2=yy;}
}while(d>1);
return pt;
}
main()
{ int xl,xr,yt,yb;
int x1,y1,x2,y2;
struct point *p1,*p2;
initgr();
printf("Enter the left,right,buttom,top edge:");
scanf("%d,%d,%d,%d",&xl,&xr,&yb,&yt);
setcolor(12);
line(xl,yt,xr,yt); line(xl,yb,xr,yb);
line(xl,yt,xl,yb); line(xr,yt,xr,yb);
printf("Enter the first point of the line:");
scanf("%d,%d",&x1,&y1);
printf("Enter the second point of the line:");
scanf("%d,%d",&x2,&y2);
setcolor(1);
line(x1,y1,x2,y2);
/*求出最靠近(x1,y1)的内点*/
p1=edgepoint(x1,y1,x2,y2,xl,xr,yb,yt);
/*求出最靠近(x2,y2)的内点*/
p2=edgepoint(x2,y2,p1->x,p1->y,xl,xr,yb,yt);
setcolor(14);
if(p1!=NULL&&p2!=NULL)
line(p1->x,p1->y,p2->x,p2->y);
else
printf("\nthe line is invisiable.");
getch();
closegraph();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -