3

我正在尝试使用 Bresenham 的算法在 C 语言中画一条线。我在 windows 7 的 dosbox 中使用 turbo C++ 来实现此代码。编译时我没有收到任何错误,但是当我运行代码时程序终止后获得2个坐标。请帮助..

编译消息如下.. 在此处输入图像描述

目录路径如下在此处输入图像描述

我的代码..

  # include <stdio.h>
  # include <conio.h>
  # include <graphics.h>

  void main()
  {
    int dx,dy,x,y,p,x1,y1,x2,y2;
    int gd,gm;

    clrscr();

    printf("\n\n\tEnter the co-ordinates of first point : ");
    scanf("%d %d",&x1,&y1);
    printf("\n\n\tEnter the co-ordinates of second point : ");
    scanf("%d %d",&x2,&y2);

    dx = (x2 - x1);
    dy = (y2 - y1);

    p = 2 * (dy) - (dx);

    x = x1;
    y = y1;

    detectgraph(&gd,&gm);
    initgraph(&gd,&gm,"e:\\tc\\bgi");
    putpixel(x,y,WHITE);

    while(x <= x2)
    {
      if(p < 0)
      {
        x=x+1;
        y=y;
        p = p + 2 * (dy);
      }
      else
      {
        x=x+1;
        y=y+1;
        p = p + 2 * (dy - dx);
     }
     putpixel(x,y,WHITE);
   }
   getch();
   closegraph();
}
4

4 回答 4

1

OP 应该发布使用过的输入。

发布的示例代码不起作用是x1>x2也不是y1> y2。这是一组会突然停止例程的输入。要修复,dxanddy应该基于绝对值,并且增量x&y步骤需要独立+1 or -1

输入3,4而不是3 4(逗号与空格)也会使例程混乱。

在 while 循环中,推荐if(p <= 0).

OP的“......代码程序在获得2个坐标后终止。” 不够详细,因为当然代码应该在获得 2 个坐标后的某个时间终止。但是 OP 没有详细说明它在哪里过早终止。

于 2013-09-23T19:01:34.490 回答
0

这是启动调试器并逐步检查代码、观察任何变量的典型完美点。如果调试器不可用,控制台的 printf 调试是备用选择。

第一个提示是检查这些行是否不会生成错误/异常:

  detectgraph(&gd,&gm);
  initgraph(&gd,&gm,"e:\\tc\\bgi");
  putpixel(x,y,WHITE);
于 2013-09-12T10:21:34.460 回答
0

Nice program. But, you haven't initialized any loop as well as lines coded in while-loop were partially incorrect. Here is my try:-

i = 1; // loop initialization
do {
    putpixel(x, y, 15);
    while(p >= 0) {
        y = y + 1;
        p = p - (2 * dx);
    }
    x = x + 1;
    p = p + (2 * dy);
    i = i + 1;
}
while(i <= dx);
于 2014-12-15T16:10:21.697 回答
0

解决问题的一种方法是根据屏幕截图中提到的地址更改 initgraph 函数中的路径。

detectgraph(&gd,&gm);
initgraph(&gd,&gm,"C:\\TURBOC3\\bgi");
putpixel(x,y,WHITE);
于 2013-09-28T10:18:54.803 回答