阅读以下说明和C程序,将填入(n)处的字句在对应栏内。 [说明] 某旅游服务应用程序运行时,根据输入
阅读以下说明和C程序,将填入 (n) 处的字句在对应栏内。
[说明]
某旅游服务应用程序运行时,根据输入的两个城市名查找其问的距离。各城市问的距离如表4-1所示。表格中的第一行和第一列表示城市名,表中的每个元素是一个整数,代表该元素所在行和列对应的城市之间的距离(单位:km)。
表4-1
在程序中,城市名用一维全局数组cityTable存储,城市之间的距离矩阵用二维全局数组kmTable表示,并用相应的值对这两个数组进行初始化。
define NCities 8 /*城市个数*/
define TRUE 1
static char * cityTable[NCities]={ /*城市名按字典序升序排列*/
"Beijing",
…… /*其他城市名略去*/
"Sanya",
};
StatiC int kmTable[NCities][NCities]={
{0, 1697, 2695, 937, 1784, 1356, 926, 2543},
{1697, 0, 313, 1840, 533, 940, 1409,1505},
…… /*剩余元素的初始值略去*/
};
程序执行时,首先按提示输入两个城市名,然后在cityTable中查找与城市名对应的下标,最后用该下标在kmTable中找到这两个城市之间的距离。
程序中定义的函数FindCitylnSortedArray和GetCity说明如下:
(1)函数FindCitylnSortedArray的功能是用二分查找法在全局数组cityTable中查找城市名所对应的下标值。
(2)函数GetCity的功能是读入城市名,调用函数FindCityInSortedArray来获取城市所对应的下标值。如果该城市名不存在,则提示用户重新输入。
[C程序]
int main() {
int city1,city2;
city1=GetCity("输入第1个城市名:");
city2=GetCity("输入第2个城市名:");
printf("%S和%s之间的距离为:%d km.\n”,cityTable[city1],
cityTable[city2],
kmTable[cityl][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); /*获取输入字符串*/
index=FindCityInSortedArray(cityName);
if((1) ________ )break;
printf("城市名不存在,请重新输入。\n");
}
free(cityName);
return (2)__________;
}
Static int FindCityInSortedArray(char * key) {
int lh, rh, mid, cmp;
lh=0;
rh=NCities-1;
while((3)________){
mid=(1h+rh)/2;
cmp=strcmp((4)______ ); /*比较两个城市名是否相同*/
if(cmp==0)return (5)_______; /*两个城市名相同*/
if(cmp<0){rh=mid-1;)
else {lh=mid+1;)
}
return (-1); /*城市名不存在时返回-1 */
}