#include<stdio.h>

 #include<stdlib.h>

 #include"graphics.h"

 //函数声明

 void MidBrehansem(int x0, int y0, int x1, int y1);  //中点MidBrehansem算法

 void swap(int &x, int &y);  //利用引用传递交换值

 int main()

 {

     int gdriver = DETECT, gmode;

     int x0, y0, x1, y1;

     printf("Please input start point:\n");

     scanf("%d%d", &x0, &y0);

     printf("Please input end point:\n");

     scanf("%d%d", &x1, &y1);

     initgraph(&gdriver, &gmode, "");

     MidBrehansem(x0, y0, x1, y1);

     system("pause");

     closegraph();

     return ;

 }

 //中点MidBrehansem算法

 void MidBrehansem(int x0, int y0, int x1, int y1)

 {

     int  dx, dy,i,di;

     double k;

     if (x0 > x1)

     {

         swap(x0, x1);

         swap(y0, y1);

     }

     int x = x0, y = y0;     //定义到前面会从x1,y1开始画线

     dx = x1 - x0;

     dy = y1 - y0;

     k = 1.0*dy / dx;

     i = (abs(dy)>abs(dx)) ? abs(dy): abs(dx);

     if (k >= )

     {

         di =  * dx + dy;

         while (i--)

         {

             putpixel(x, y, RED);

             if (di >= )

             {

                 di +=  * (dx - dy);

                 x++;

             }

             else

                 di +=  * dx;

             y++;

         }

     }

     else if (k >=  && k < )

     {

         di = dx -  * dy;

         while (i--)

         {

             putpixel(x, y, YELLOW);

             if (di < )

             {

                 di +=  * (dx - dy);

                 y++;

             }

             else

                 di += (-)*dy;

             x++;

         }

     }

     else if (k >= - && k < )

     {

         di = -dx -  * dy;

         while (i--)

         {

             putpixel(x, y, YELLOW);

             if (di >= )

             {

                 di += (-)*(dx + dy);

                 y--;

             }

             else

                 di += (-)*dy;

             x++;

         }

     }

     else

     {

         di = - * (dx + dy);

         while (i--)

         {

             putpixel(x, y, WHITE);

             if (di < )

             {

                 di += (-)*(dx + dy);

                 x++;

             }

             else

                 di += (-)*dx;

             y--;

         }

     }

 }

 //利用引用传递交换值

 void swap(int &x, int &y)

 {

     int t;

     t = x;

     x = y;

     y = t;

 }

中点Brehensam画线算法-LMLPHP中点Brehensam画线算法-LMLPHP中点Brehensam画线算法-LMLPHP中点Brehensam画线算法-LMLPHP

05-11 11:09