需要帮助。我必须编写Djikstra算法的程序,不必从用户处获取任何输入,只需在程序中硬编码即可。这是我第一次用C语言编写任何东西,对它并不是很擅长。我已经在头脑中想好了代码的逻辑运行方式,但问题是当我运行它时,什么也没有输出。如果有人能帮我找到问题,那就太好了。我会继续更新进展情况,但比我更聪明的C语言专家可能更容易找到问题。
#include <stdio.h>
void main (){
int ab = 3;//path from a to b
int ac = 7;//path from a to c
int ad = 9;//path from a to d
int bc = 2;//path from b to c
int bd = 4;//path from b to d
int cd = 1;//path from c to d
int a = 10;//number values for position
int b = 20;
int c = 30;
int d = 40;
int position = 10;//starting position a
int currenttravel = 0;
//starting at a
//if (position == 10){
int checker = 40;//check for when at d
do
{
//check for if at a
if (position == 10){
//if path a to b is shortest
if (ab < ac && ab < ad){
position = b;//go to b
printf("%d", &position);
currenttravel+=ab;
}
//or if path a to c is shortest
else if (ac < ad){
position = c;//go to c
printf("%d", &position);
currenttravel+=ac;
}
else{
position = d;
printf("%d", &position);
currenttravel+=ad;
}
}
if (position == 20)//at b
{
if (bc < bd){
position = c;
printf("%d", &position);
currenttravel+=bc;
}
else{
position = d;
printf("%d", &position);
currenttravel+=bd;
}
}
if (position == 30){
position = d;
printf("%d", &position);
currenttravel+=cd;
}
}
while(position != checker);
// }//end if start position is a
printf("%d", currenttravel);
return; //leave function
}
我已尽力进行注释,希望您能够理解我的逻辑。我可能过于复杂化了这个问题,但这应该是一种可能的解决方法。
修复后可正常工作的代码!
#include <stdio.h>
int main (){
int ab = 3;//path from a to b
int ac = 7;//path from a to c
int ad = 9;//path from a to d
int bc = 2;//path from b to c
int bd = 4;//path from b to d
int cd = 1;//path from c to d
int a = 10;//number values for position
int b = 20;
int c = 30;
int d = 40;
int position = 10;//starting position a
int currenttravel = 0;
//starting at a
//if (position == 10){
int checker = 40;//check for when at d
do
{
printf("starting at a \n");
//check for if at a
if (position == a){
//if path a to b is shortest
if (ab < ac && ab < ad){
position = b;//go to b
printf("b \n");
currenttravel+=ab;
}
//or if path a to c is shortest
else if (ac < ad){
position = c;//go to c
printf("c \n");
currenttravel+=ac;
}
else{
position = d;
printf("d \n");
currenttravel+=ad;
}
}
if (position == b)//at b
{
if (bc < bd){
position = c;
printf("c \n");
currenttravel+=bc;
}
else{
position = d;
printf("d \n");
currenttravel+=bd;
}
}
if (position == c){
position = d;
printf("d \n");
currenttravel+=cd;
}
}
while(position != checker);
// }//end if start position is a
printf("%d", currenttravel);
// return; //leave function
}
感谢大家的帮助。现在我只需要将它转换为普里姆算法(这将非常简单,因为我只是不将所有内容相加)。也许会尝试不同的起始位置,但现在这已经足够了。
\n
,它们将会显示出来。而且不要传递指针,例如printf("%d\n", position);
。 - bruceg