第六套上機(jī)試題
一、改錯(cuò)題
含有錯(cuò)誤的源程序:
#include
#include
#define N 5
struct student
{ char name[10];
int score;
} ―――――――――――①
void sort(struct student stud[],int n)
{ int i,j;
struct student p;
for(i=1;i
{ p=stud[i];
for(j=i-1;j>0 && p>stud[j];j--) ―――――――――――③
stud[j+1]=stud[j];
stud[j+1]=p;
}
}
void main()
{ struct student stud[N]={"aaa",60,"bbb",90,"ccc",85,"ddd",65,"yyy",77};
int i;
sort(stud,N);
printf("sorted data:\n");
for(i=0;i
}
【知識(shí)點(diǎn)】結(jié)構(gòu)體、排序
【難點(diǎn)】 插入法排序
【解析】本題是將未排序的數(shù)組元素采用插入排序方法進(jìn)行排序,其思想是:從第2個(gè)元素開始,最初與第一個(gè)元素進(jìn)行比較,由大到小排列在適當(dāng)位置,成為排好序的數(shù)組元素一員。再依次將待排序的元素與前面已排好序的元素從后向前進(jìn)行比較,如果大于該元素,則該元素向后移一位,直到待排序的元素小于已排好序的某一元素,則直接插入到該元素之后。直到待排序的元素全部完成為止。本程序的sort函數(shù)中i表示待排序的元素下標(biāo),j表示已排好序的元素下標(biāo)。
【答案】(1)標(biāo)號(hào)①:} 改為 }; (2)標(biāo)號(hào)②:for(i=1;i
(3)標(biāo)號(hào)③:for(j=i-1;j>0 && p>stud[j];j--) 改為 j>=0 && p.score>stud[j].score;j--)
(4) 標(biāo)號(hào)④:printf("%s\t%d\n",stud[i]); 改為printf("%s\t%d\n",stud[i].name,stud[i].score );
二、編程題
【知識(shí)點(diǎn)】字符串操作、函數(shù)、文件
【解析】仔細(xì)閱讀并分析【編程要求】?!揪幊桃?】已對(duì)函數(shù)Replace_string指定了函數(shù)名、函數(shù)類型、形參類型和個(gè)數(shù),并詳細(xì)說明了其功能。在line指向的字符串中查找str1指向的字符子串的關(guān)鍵語句是當(dāng)“str1[j]= =line[loc]&&str1[j]!='\0'”時(shí)繼續(xù)循環(huán)查找,當(dāng) 因“str1[j]!='\0'”退出循環(huán)時(shí),則找到str1指向的字符子串,此時(shí)用str2指向的字符串替換在line中的str1字符子串,返回?!揪幊桃?】編寫主函數(shù)主要功能要求是保存結(jié)果到數(shù)據(jù)文件、調(diào)用Replace_string函數(shù)、輸入測(cè)試數(shù)據(jù)。這部分是最常規(guī)和基本的要求,必須掌握。
【參考答案】
#include
#include
int Replace_string (char line[],char str1[],char str2[])
{ int i=0,j,loc;
char temp[80];
while(i<=strlen(line)-strlen(str2))
{ j=0;loc=i;
while(str1[j]= =line[loc]&&str1[j]!='\0')
{ loc++;j++;}
if(str1[j]= ='\0')
{strcpy(temp,&line[loc]);strcpy(&line[i],str2);
i+=strlen(str2);strcpy(&line[loc],temp);
return 1;
}
else i++;
}
return 0;
}
main()
{ FILE *fp;
char string[100]="My EXAM_number is 0112404321.";
char number[11]="0112404321",num[11];
fp=fopen("myf2.out","w");
fprintf(fp,"%s\n",string);
gets(num);
Replace_string (string,number,num);
fprintf(fp,"%s\n",string);
fprintf(fp,"\n my exam number is: %s\n","0112404321");
fclose(fp); }

