計(jì)算機(jī)等級(jí)考試三級(jí)編程解析八

字號(hào):

八、數(shù)字或字符移位后的計(jì)算
    已知在文件in.dat中存有若干個(gè)(個(gè)數(shù)<200)四位數(shù)字的正整數(shù),函數(shù)readdat
    ()讀取這若干個(gè)正整數(shù)并存入數(shù)組xx中。請(qǐng)編制函數(shù)calvalue(),其功能要求:1、求出
    這文件中共有多少個(gè)正整數(shù)totnum;2、求這些數(shù)右移1位后,產(chǎn)生的新數(shù)是偶數(shù)的數(shù)的
    個(gè)數(shù)totcnt,以及滿足此條件的這些數(shù)(右移前的值)的算術(shù)平均值totpjz,最后調(diào)用
    函數(shù)writedat()把所求的結(jié)果輸出到文件out.dat中。
    部分源程序已給出。
    請(qǐng)勿改動(dòng)主函數(shù)main()、讀數(shù)據(jù)函數(shù)readdat()和輸出數(shù)據(jù)函數(shù)writedat()的內(nèi)容。
    #include
    #include
    #define MAXNUM 200
    int xx[MAXNUM];
    int totnum=0;
    int totcnt=0;
    double totpjz=0.0;
    int readdat(void);
    void writedat(void);
    void calvalue(void)
    {
    }
    void main()
    {
    int i;
    clrscr();
    for(i=0;iif(readdat())
    {printf("Can’t open the data file in.dat!\007\n");
    return;
    }
    calvalue();
    printf("totnum=%d\n",totnum);
    printf("totcnt=%d\n",totcnt);
    printf("totpjz=%.2lf\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%.2lf\n",totnum,totcnt,totpjz);
    fclose(fp);
    }
    /* 注:本題用if(!xx[i]) break;來判斷xx[i]是否為0,若是則跳出循環(huán)。亦是較簡單。*/
    void calvalue(void)
    {
    int i,data;
    for(i=0;i{if(!xx[i]) break;
    if(xx[i]>0) totnum++;
    data=xx[i]>>1;
    if(data%2==0)
    {totcnt++;
    totpjz+=xx[i];
    }
    }
    totpjz/=totcnt;
    }