printf调试。 while循环执行,第一个for循环执行,第二个for循环不执行。
while (size > 0){
printf("in the while loop!\n");
VertexPointer current = graph[0];
int i;
for (i = 1; i < size; i++){
float dist = 0;
printf("in the first for loop for i = %d \n", i);
int j;
for(j = 0; j++; j < dimension){
printf("dist loop: %d\n", j);
printf("current: %f\n", (*current).loc[0]);
printf("unvisited: %f\n", (*graph[j]).loc[0]);
dist = dist + pow((*current).loc[0] + (*graph[j]).loc[0], 2);
printf("distance: %f", dist);
dist = sqrt(dist);
if (dist < (*graph[i]).key){
decreaseKey(graph, i, dist);
}
}
}
extractMin(graph, size);
size = size - 1;
mst_length = mst_length + (*current).key;
}
最佳答案
你切换了条件和增量:
for(j = 0; j++; j < dimension)
因此循环测试 j++
的值,并且由于后缀 ++
运算符返回它递增的变量的 previous 值,它将在第一次迭代时返回 0(j
的初始值),因此永远不会循环。改成
for(j = 0; j < dimension; j++)
如果您打开警告,您应该会收到一条消息,表明第三个表达式没有副作用(并且会被编译器优化掉)。
或者(停止:实际上不要这样做):
将条件更改为 ++j
以使其成为(可能)永无止境的循环:
for(j = 0; ++j; j < dimension)
如果你很幸运(在这种情况下通常是这样),循环将在 j
达到 MAX_INT
并返回到 0 时结束。但标准不会不能保证,所以它可能是无穷无尽的。
关于c - 为什么第二个for循环不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22262095/