输入两个城市名查找其间的距离(note)

输入两个城市名查找其间的距离。
FindCityInsorArray用二分查找法在全局函数cityTable中查找城市名对应的下标值。
/* malloc example: random string generator*/
#include <stdio.h> /* printf, scanf, NULL /
#include <stdlib.h> /
malloc, free, rand */
#define NCities 8
#define TRUE 1

static char * cityTable[NCities] = {
“beijing”, “chengdu”, “chongqing”, “dalian”, “guiyang”, “lanzhou”, “nanjing”, “sanya”
};
static int kmTable[NCities][NCities] = {
{0, 1697, 2695, 937, 1784, 1356, 926, 2543},
{1697, 0, 313, 1840, 533, 940, 1409, 1505},
{2695, 313, 0, 1734, 343, 1117, 1206, 1306},
{937, 1840, 1734, 0, 1995, 1594, 818, 2602},
{1784, 533, 343, 1995, 0, 1113, 1346, 976},
{1356, 940, 1117, 1594, 1113, 0, 1654, 2075},
{926, 1409, 1206, 818, 1346, 1654, 0, 1806},
{2543, 1505, 1306, 2602, 976, 2075, 1806, 0}
};

int main (){
int city1,city2;
city1 = GetCity(“input first city name:”);
city2 = GetCity(“input secend city name:”);
printf(“distant: %d km.\n”,cityTable[city1],cityTable[city2],kmTable[city1][city2]);
return 0;
}
static int GetCity(char * prompt){
char * cityName;
int index;
cityName = (char*)malloc(20*sizeof(char));
while(TRUE){
printf("%s",prompt);
gets(cityName); expand1 expand2
index = FindCityInSortArray(cityName);
if(index >= 0) break;
printf(“no city.\n”);
}
free(cityName);
return index;
}
二分查找法:
static int FindCityInSortArray(char * key){
int lh,rh,mid,cmp;
lh = 0;
rh = NCities - 1;
while(lh<= rh){
mid = (lh + rh) / 2;
cmp = strcmp(key, cityTable[mid]); expand3 expand4
if(cmp == 0) return mid;
if(cmp < 0){
rh = mid -1;
}
else{
lh = mid +1;
}
}
return(-1);
}
C++ 读取键盘输入(cin/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值