1、计算机三级数据库技术-148 及答案解析(总分:100.00,做题时间:90 分钟)一、上机题(总题数:1,分数:100.00)1.已知数据文件 IN.DAT 中存有 300 个 4 位数,并已调用读函数 readDat()把这些数存入数组 a 中,请编写函数 jsValue(),其功能是:求出这些 4 位数中素数的个数 cnt,再把所有满足此条件的 4 位数依次存入数组 b 中,然后对数组 b 的 4 位数按从小到大的顺序进行排序,最后调用函数 writeDat(),把数组 b中的数输出到 OUT.DAT 文件中。 例如,5591 是素数,则该数满足条件,存入数组 b 中,且个数 cnt=c
2、nt+1。 9812 是非素数,则该数不满足条件,忽略。 注意:程序中已定义数组 a300、b300,已定义变量 cnt。请勿改动主函数 main()、读函数 readDat()和写函数 writeDat()的内容。 【试题程序】 #include stdio .h int a300,b300,cnt=0; void readDat () ; void writeDat () ; int isP (int m) int i ; for (i =2;i m;i + ) if (m%i = 0 ) return 0 ; return 1 ; void jsValue () void main ()
3、 int i ; readDat () ; j sValue () ; writeDat () ; printf (“cnt =%dn“, cnt) ; for (i =0;i cnt;i + ) printf (“b%d =%dn“,i,bi) ; void readDat () FILE * fp; int i ; fp = fopen ( “IN. DAT“, “r“ ) ; for (i =0;i 300;i + ) fscanf (fp, “%d, “, fclose (fp) ; void writeDat () FILE * fp; int i; fp = fopen ( “OU
4、T. DAT“, “w“ ) ; fprintf (fp, “%dn“, cnt) ; for(i=0;icnt;i+) fprintf (fp, “%dn“,bi ) ; fclose (fp) ; (分数:100.00)_计算机三级数据库技术-148 答案解析(总分:100.00,做题时间:90 分钟)一、上机题(总题数:1,分数:100.00)1.已知数据文件 IN.DAT 中存有 300 个 4 位数,并已调用读函数 readDat()把这些数存入数组 a 中,请编写函数 jsValue(),其功能是:求出这些 4 位数中素数的个数 cnt,再把所有满足此条件的 4 位数依次存入数组
5、b 中,然后对数组 b 的 4 位数按从小到大的顺序进行排序,最后调用函数 writeDat(),把数组 b中的数输出到 OUT.DAT 文件中。 例如,5591 是素数,则该数满足条件,存入数组 b 中,且个数 cnt=cnt+1。 9812 是非素数,则该数不满足条件,忽略。 注意:程序中已定义数组 a300、b300,已定义变量 cnt。请勿改动主函数 main()、读函数 readDat()和写函数 writeDat()的内容。 【试题程序】 #include stdio .h int a300,b300,cnt=0; void readDat () ; void writeDat (
6、) ; int isP (int m) int i ; for (i =2;i m;i + ) if (m%i = 0 ) return 0 ; return 1 ; void jsValue () void main () int i ; readDat () ; j sValue () ; writeDat () ; printf (“cnt =%dn“, cnt) ; for (i =0;i cnt;i + ) printf (“b%d =%dn“,i,bi) ; void readDat () FILE * fp; int i ; fp = fopen ( “IN. DAT“, “r“
7、 ) ; for (i =0;i 300;i + ) fscanf (fp, “%d, “, fclose (fp) ; void writeDat () FILE * fp; int i; fp = fopen ( “OUT. DAT“, “w“ ) ; fprintf (fp, “%dn“, cnt) ; for(i=0;icnt;i+) fprintf (fp, “%dn“,bi ) ; fclose (fp) ; (分数:100.00)_正确答案:()解析:void jsValue() int i,j; /*定义循环控制变量*/ int temp; /*定义数据交换是的暂存变量*/ f
8、or(i=0;i300;i+) /*逐个取 4 位数*/ if(isP(ai) /*如果该数为素数,则将该数存入数组 b 中*/ bcnt=ai; cnt+; /*并统计满足条件的数的个数*/ for(i=0;icnt-1;i+) /*对数组 b 的 4 位数按从小到大的顺序进行排序*/ for(j=i+1;jcnt;j+) if(bibj) temp=bi; bi=bj; bj=temp; 解析 本题属于数学类题。根据题意可知,函数 jsValue()要实现两个功能:一是找出为素数的数,并存放在数组 b 中;二是对数组 b 中的数进行从小到大的排序。 首先要找出满足条件的数,即素数,题目中已给出了判断素数的函数,因此只需调用即可。 其次,将这些素数存入数组 b 中,并用变量 cnt 来统计数组 b 中元素的个数。 最后,将所有满足条件的数取出后利用起泡法进行排序,即将当前元素依次同它后面的元素进行比较,发现有大于该数的数,就将这两个数进行交换。