为什么这个代码在我的机器上显示正确的值时却显示一些垃圾类型的值
Why is this code showing some junk type of value when it shows the correct value on my machine?
我正在尝试编写一个代码来实现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上的代码(还删除了一些未使用的变量)。
相关文章:
- 在模板中显示参数的类型
- 实例化模板时,我是否必须显式显示参数包中的类型?
- 运算符重载以显示用户定义的数据类型
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- C++如何在类Vector中显示不同类型的参数
- 回调方法显示错误,类型为"void(*)"的值不能用于初始化类型的实体
- C 尝试使用模板输出功能来显示不同类型的数据
- boost::variant 当 bool 显示为可能的类型时,会给出错误的结果
- VIM:执行复杂文件类型的脚本和显示结果
- 开关(事件类型)不工作和计时器不显示
- 在 c++ 中显示任何类型的结构的通用函数
- 显示为数据类型的纯虚拟类
- 以C++显示浮点类型的二进制表示形式
- 此背包代码显示浮点[float]无效类型错误.可能是什么原因
- 类型限定符出现在多项声明中(用指针显示奇怪的行为)
- 是否有类型特征显示一种类型是否可能包含其他类型的值
- C++ 显示字符串变量"<不完整类型>的调试窗口
- Switch语句不显示除默认语句之外的任何类型的输出
- 使QT/C 程序显示其文件类型,如Windows上已知
- lldb 可以显示类型定义的实际类型吗?