閱讀以下說(shuō)明和C 程序,將應(yīng)填入(n)處的字句寫(xiě)在答題紙的對(duì)應(yīng)欄內(nèi)。
【說(shuō)明】
某旅游服務(wù)應(yīng)用程序運(yùn)行時(shí),根據(jù)輸入的兩個(gè)城市名查找其間的距離。各城市間的距離如表4-1所示。表格中的第一行和第一列表示城市名,表中的每個(gè)元素是一個(gè)整數(shù),代表該元素所在行和列對(duì)應(yīng)的城市之間的距離(單位:km)。
程序中定義的函數(shù)FindCityInSortedArray和GetCity說(shuō)明如下:
(1)函數(shù) FindCityInSortedArray 的功能是用二分查找法在全局?jǐn)?shù)組 cityTable 中查找城市名所對(duì)應(yīng)的下標(biāo)值。
(2)函數(shù)GetCity的功能是讀入城市名,調(diào)用函數(shù)FindCityInSortedArray來(lái)獲取城市所對(duì)應(yīng)的下標(biāo)值。如果該城市名不存在,則提示用戶重新輸入。
【C 程序】
int main ( ) {
int city1,city2;
city1 = GetCity("輸入第 1個(gè)城市名: ") ;
city2 = GetCity("輸入第 2 個(gè)城市名: ");
printf(" %s 和%s之間的距離為:%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) ; /*獲取輸入字符串*/
index = FindCityInSortedArray(cityName);
if ( (1) ) break;
printf(" 城市名不存在,請(qǐng)重新輸入。 \n") ;
}
free(cityName);
return (2);
}
static int FindCityInSortedArray(char*key) {
int lh ,rh ,mid ,cmp;
lh = 0;
rh = NCities - 1;
while ( (3) ) {
mid = (lh + rh) / 2;
cmp = strcmp ( (4) ); /*比較兩個(gè)城市名是否相同*/
if (cmp == 0) return (5); /*兩個(gè)城市名相同*/
if (cmp < 0) { rh = mid - 1; }
else { lh = mid + 1; }
}
return (-1); /*城市名不存在時(shí)返回 -1 */
}