为什么这个代码在我的机器上显示正确的值时却显示一些垃圾类型的值

Why is this code showing some junk type of value when it shows the correct value on my machine?

本文关键字:显示 类型 代码 我的 为什么 机器      更新时间:2023-10-16

我正在尝试编写一个代码来实现Djistra的算法。。。还有一些问题代码的链接是Ideone。。。当相同的代码在我的电脑上运行时,输出是

0 4 12 19 21 11 9 8 14

一个视频的输出是

0 4 12 19 21 11 9 8 16777230

看看最后一个元素14中的区别……我对此一无所知……我的代码中有错误吗?或者是由于在线编译器的其他原因,或者我在做一些愚蠢的事情?

此处存在潜在错误

int find(int start)
{
int low=INT_MAX,idx=-1,i;
for(i=0;i<V;i++)
if( !(Left[i]) && low>=Distances[i])
{
idx=i;
low=Distances[i];
}
return idx;
}
while(start != -1)
{
for(i = 0; i < V; i++)
if(graph[start][i] && Distances[start] + graph[start][i] < Distances[i])
Distances[i] = graph[start][i] + Distances[start];
start = find(start);
Left[start] = true;
}

我试着找出原因。。V-1的距离在某个时候是14(我试过打印它),但后来没有更新(我试着在V-1距离更新时打印它)但后来似乎没有更新!!我是初学者,请告诉我哪里错了注:(Graph是2D邻接矩阵)Distances是int类型的数组,Left是bool类型的数组)

您在ideone上的代码中的while循环中有未定义的行为,这与您在此处发布的代码不匹配。这就是为什么别人告诫你没有提供一个最小的例子。当find返回-1时,Left[start] = true在数组开始之前进行访问。由于它是未定义的行为,它可以做任何事情,包括在你的电脑上正常工作和在ideone上失败。要修复此问题,由于while循环之前有一个Left[start] = true,请将其移除,并将其移动到while的顶部:

while(start != -1)
{
Left[start] = true;
for(i = 0; i < V; i++)
if(graph[start][i] && Distances[start] + graph[start][i] < Distances[i])
Distances[i] = graph[start][i] + Distances[start];
start = find(start);
}

更正了ideone上的代码(还删除了一些未使用的变量)。