二级B上级模拟试题及答案(2)

全国等级考试资料网 2022-08-19 05:00:33 134
请编制函数readdat( )实现从文件fc.in中读取1000个十进制  整数到数组xx中; 请编制函数compute()分别计算出xx中奇数的个  数odd, 偶数的个数even, 平均值aver以及方差totfc的值, 最后调  用函数writedat()把结果输出到fc1.out文件中。 
计算方差的公式如下: 
1 n 
totfc = ── ∑ (xx - aver)^2 
n i=1 
原始数据文件存放的格式是: 每行存放10个数, 并用逗号隔 
开。(每个数均大于0且小于等于2000) 
注意: 部分源程序存放在prog1.c中。 
请勿改动主函数main()和输出数据函数writedat()的内容。 

/*参考答案*/ 

#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 ; 

/***********读入数据并存放到数组xx中*************/ 
for(i = 0; i < max; i++) 

j = 0; 

while((c = (char) fgetc(fp)) != eof) 

if(c == ’,’) 

str[j] = ’’; 
break; 


else if(c != ’ ’ && c != ’ ’)/*去掉回车换行符*/ 

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("数据文件fc.in不能打开!07 ") ; 
return ; 

compute() ; 
printf("odd=%d oven=%d aver=%lf totfc=%lf ", odd, even, aver, totfc) ; 
writedat() ; 


void writedat(void) 

file *fp ; 
int i ; 

fp = fopen("fc1.out", "w") ; 
fprintf(fp, "%d %d %lf %lf ", odd, even, aver, totfc) ; 
fclose(fp) ; 
相关资料

相关阅读