我有一个非常愚蠢的问题,现在已经困扰了我几个小时。我已经制作了一个程序来比较一个点阵列的斜率,并绘制一条线,通过相同斜率的四个点。我的问题是我把初始斜率作为每个斜率的比较器。然后将初始值与阵列中的每个其他点进行比较,如果初始比较器的斜率与下一个斜率相同,则计数器递增。我的问题是我想要在for循环期间改变初始斜率,但我不能让它工作。代码在下面,我知道我有点模糊,所以如果你需要更多的信息,请问。
for(int initial = 0; initial < counter/2 ; initial ++)
{
int comparator = 1;
for(int next = 1 ; next < counter/2 ; initial ++)
{
Point finalCompare = points[initial];
Point initialCompare = points[comparator];
Point initialPoint = points[initial];
int counter_2 = 0;
Point nextPoint = points[next];
double initialSlope = (initialCompare.y - initialPoint.y/ initialCompare.x-initialPoint.x);
double nextSlope = (nextPoint.y - initialPoint.y/ nextPoint.x - initialPoint.x);
if(initialSlope == nextSlope)
{
counter_2++;
StdOut.println("Counter: " + counter_2);
finalCompare = points[next];
}
if(counter_2 >= 3)
{
StdOut.println("got here");
initialPoint.drawTo(finalCompare);
break;
}
StdOut.println(counter_2);
}
StdOut.println("comparator");
comparator++;
}
}
答案 0 :(得分:3)
你永远不会改变next
。我想你想要
for(int next = 1 ; next < counter/2 ; next++)
而不是
for(int next = 1 ; next < counter/2 ; initial ++)
此外,这种情况似乎永远不会成真:if(counter_2 >= 3)
您将counter_2
设置为0并在此语句之前最多增加一次:
int counter_2 = 0;
...
if(initialSlope == nextSlope)
{
counter_2++;
...
}
//counter_2 can either be 0 or 1 here
if(counter_2 >= 3)
{
...
}
我假设您要将初始化移出内循环:
int counter_2 = 0;
for(int next = 1 ; next < counter/2 ; next++)
除此之外,请使用调试器逐步执行代码,并查看每个步骤的操作。这将帮助您找到输入错误(如果您了解正在实施的算法,否则请先尝试理解)。
答案 1 :(得分:0)
这些行
double initialSlope = (initialCompare.y - initialPoint.y/ initialCompare.x-initialPoint.x);
double nextSlope = (nextPoint.y - initialPoint.y/ nextPoint.x - initialPoint.x);
我认为他们没有做你想做的事,请记住/优先,所以首先要划分initialPoint.y / initialCompare.x,然后其余的操作,我想你想做:
double initialSlope = ((initialCompare.y - initialPoint.y)/ (initialCompare.x-initialPoint.x));
double nextSlope = ((nextPoint.y - initialPoint.y)/ (nextPoint.x - initialPoint.x));