二級(jí)B上級(jí)模擬試題及答案(2)

字號(hào):

請(qǐng)編制函數(shù)readdat( )實(shí)現(xiàn)從文件fc.in中讀取1000個(gè)十進(jìn)制 整數(shù)到數(shù)組xx中; 請(qǐng)編制函數(shù)compute()分別計(jì)算出xx中奇數(shù)的個(gè) 數(shù)odd, 偶數(shù)的個(gè)數(shù)even, 平均值aver以及方差totfc的值, 最后調(diào) 用函數(shù)writedat()把結(jié)果輸出到fc1.out文件中。
    計(jì)算方差的公式如下:
    1 n
    totfc = ── ∑ (xx - aver)^2
    n i=1
    原始數(shù)據(jù)文件存放的格式是: 每行存放10個(gè)數(shù), 并用逗號(hào)隔
    開。(每個(gè)數(shù)均大于0且小于等于2000)
    注意: 部分源程序存放在prog1.c中。
    請(qǐng)勿改動(dòng)主函數(shù)main()和輸出數(shù)據(jù)函數(shù)writedat()的內(nèi)容。
    /*參考答案*/
    #include
    #include
    #include
    #define max 1000
    int xx[max], odd = 0, even = 0 ;
    double aver = 0.0 , totfc = 0.0 ;
    void writedat(void) ;
    int readdat(void)
    {
    file *fp ;
    int i,j;
    char c,str[20];
    if((fp = fopen("fc.in", "r")) == null) return 1 ;
    /***********讀入數(shù)據(jù)并存放到數(shù)組xx中*************/
    for(i = 0; i < max; i++)
    {
    j = 0;
    while((c = (char) fgetc(fp)) != eof)
    {
    if(c == ’,’)
    {
    str[j] = ’\0’;
    break;
    }
    else if(c != ’\n’ && c != ’\r’)/*去掉回車換行符*/
    {
    str[j] = c;
    ++j;
    }
    }
    xx = atoi(str);
    if(c == eof)
    break;
    }
    fclose(fp) ;
    return 0 ;
    }
    void compute(void)
    {
    int i;
    long count = 0;
    for(i = 0; i < max; i++)
    {
    if(xx & 1)
    odd++;
    else
    even++;
    count += xx;
    }
    aver = (double)count/max;
    for(i = 0; i < max; i++)
    totfc += (xx - aver)*(xx - aver);
    totfc /= max;
    }
    void main()
    {
    int i ;
    for(i = 0 ; i < max ; i++) xx = 0 ;
    if(readdat()) {
    printf("數(shù)據(jù)文件fc.in不能打開!\007\n") ;
    return ;
    }
    compute() ;
    printf("odd=%d\noven=%d\naver=%lf\ntotfc=%lf\n", odd, even, aver, totfc) ;
    writedat() ;
    }
    void writedat(void)
    {
    file *fp ;
    int i ;
    fp = fopen("fc1.out", "w") ;
    fprintf(fp, "%d\n%d\n%lf\n%lf\n", odd, even, aver, totfc) ;
    fclose(fp) ;
    }