gpt4 book ai didi

java - Bresenham 直线算法错误

转载 作者:太空宇宙 更新时间:2023-11-04 13:30:13 24 4
gpt4 key购买 nike

我试图用星星(*)填充矩阵来绘制布雷森汉姆线,但是当我打印出这个东西时,矩阵只填充了一颗星星,我不知道出了什么问题。语言是Java

public class PtLine extends VectorObject{   // inherites from another class
private int bx;
private int by;
private int delX;
private int delY;

public PtLine(int id,int x,int y,int bx,int by){
super(id,x,y);
this.bx = bx;
this.by = by;
this.delX = this.bx-x;
this.delY = this.by-y;

}
public void draw ( char [][] matrix ){ // filling the martic with stars
int D = 2*delY - delX;
matrix[x][y] = '*';
int j = y;

for (int i=x+1;i==bx;i++){
if(D > 0){
j+=1;
matrix[i][j]='*';
D = D + (2*delY-2*delX);
}
else{
matrix[i][j]='*';
D = D + (2*delY);
}
}
}

}

以下代码是我尝试打印矩阵时的代码

  class Question3{
public static void main ( String args [] ){


char[][] matrix = new char[20][20];
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
matrix[y][x] = ' ';
}
}

PtLine n = new PtLine(6,6,6,13,13);
n.draw(matrix);
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 20; x++) {
System.out.print(matrix[x][y]);
}
System.out.println();
}
}

}

最佳答案

您可能必须将 i==bx 更改为 i!=bx:

public void draw ( char [][] matrix ){    // filling the martic with stars
int D = 2*delY - delX;
matrix[x][y] = '*';
int j = y;

for (int i=x+1;i!=bx;i++){ // here
...
}
}

当此条件为真时,for 循环将继续。在您的代码循环中,在第一次迭代之前,循环在开始时立即结束,因为此条件为 false。

关于java - Bresenham 直线算法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32278452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com