2006年9月全國等級考試三級c語言上機題庫(二十六)

★題目26(無憂id 37 整數統計運算題)

 

已知在檔案in.dat中存有若干個(個數<200)四位數字的正整數,函式readdat()讀取這若干個正整數並存入數組xx中。請編制函式calvalue(),其功能要求:1、求出這檔案中共有多少個正整數totnum;2、求這些數右移1位後,產生的新數是偶數的數的個數totcnt,以及滿足此條件的這些數(右移前的值)的算術平均值totpjz,最後調用函式writedat()把所求的結果輸出到檔案out.dat中。

部分源程式存在檔案prog1.c中。

請勿改動主函式main()、讀函式readdat()和寫函式writedat()的內容。

#include <stdio.h>

#include <conio.h>

#define maxnum 200

 

int xx[maxnum];

int totnum=0; /*檔案in.dat中共有多少個正整數*/

int totcnt=0; /*符合條件的正整數的個數*/

double totpjz=0.0; /*平均值*/

 

int readdat(void);

void writedat(void);

 

void calvalue(void)

{int i,data;

for(i=0;i<maxnum;i++)

if(xx[i]>0)

{ totnum++;

data=xx[i]>>1;

if(data%2==0){totcnt++;totpjz+=xx[i];}

}

if(totcnt==0) totpjz=0;

else totpjz/=totcnt;

}

 

void main()

{

int i;

clrscr();

for(i=0;i<maxnum;i++)xx[i]=0;

if(readdat()){

printf("數據檔案in.dat不能打開!\007\n");

return;

}

calvalue();

printf("檔案in.dat中共有正整數=%d個\n",totnum);

printf("符合條件的正整數的個數=%d個\n",totcnt);

printf("平均值=%.2f\n",totpjz);

writedat();

}

 

int readdat(void)

{

file *fp;

int i=0;

 

if((fp=fopen("in.dat","r"))==null) return 1;

while(!feof(fp)){

fscanf(fp,"%d,",&xx[i++]);

}

fclose(fp);

return 0;

}

 

void writedat(void)

{

file *fp;

fp=fopen("out.dat","w");

fprintf(fp,"%d\n%d\n%6.2f\n",totnum,totcnt,totpjz);

fclose(fp);

}