我想创建一个程序,告诉你你选择的两个城市之间的距离(有3个城市,你可以选择2个),我写了代码,但是在我输入city1和city2后它没有输出。我是初学者,我听说strcmp
但是还有其他办法吗?这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int main()
{
char city1[] = "Zurich";
char city2[] = "Vienna";
char city3[] = "Berlin";
char location[20];
char destination[20];
puts("Which city are you in at the moment?");
gets(location);
puts("Which city do you want to go to?");
gets(destination);
if(location == city1)
{
if(destination == city2)
{
printf("Distance between %s and %s is 743km and it will take you 7 hours and 40 minutes to get there", city1, city2);
}
else
{
printf("Distance between %s and %s is 844km and it will take you 8 hours and 40 minutes to get there", city1, city3);
}
}
else if(location == city2)
{
if(destination == city3)
{
printf("Distance between %s and %s is 640km and it will take you 7 hours and 15 minutes to get there", city2, city3 );
}
else
{
printf("Distance between %s and %s is 743km and it will take you 7 hours and 40 minutes to get there", city2, city1);
}
}
return 0;
}
答案 0 :(得分:1)
location == city1
正在比较指针地址,它们将不相等。
您需要使用!strcmp(location, city1)
&amp; c。代替。如果字符串 contents 相同,则strcmp
返回0。