应用题
2. 已知在in.dat中存有若干个(个数<200)四位数字的正整数,函数ReadDat()读取这若干个正整数并存入数组xx中。请编制函数CalValue(),其功能要求:1.求出该文件中共有多少个正整数totNum;2.求这些正整数右移1位二进制位后,产生的新数是奇数的数的个数totCnt,以及满足此条件的这些正整数(右移前的值)的算术平均值totPjz。最后main()函数调用函数WriteDat()把所求的结果输出到文件out.dat中。
请勿改动数据文件in.dat中的任何数据,主函数main()、读函数ReadDat()和输出函数WriteDat()的内容。
#include <stdio.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)
{
}
void main()
{
int i;
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("平均值=%.2lf\n", totPjz);
WriteDat();
}
/*读取这若干个正整数并存入数组xx中*/
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;
}
/*把计算结果存入文件out.dat中*/
void WriteDat(void)
{
FILE *fp;
fp=fopen("out.dat", "w");
fprintf(fp, "%d\n%d\n%.2lf\n", totNum, totCnt, totPjz);
fclose(fp);
}
【正确答案】int i, j;
long he=0;
for(i=0; i<MAXNUM; i++)
if(xx[i])
totNum++;
for(i=0; i<totNum; i++)
{
j=(xx[i]>>1);
if(j%2) //如果j是奇数
{
totCnt++;
he+=xx[i];
}
}
totPjz=(double)he/totCnt;
【答案解析】 读取正数,统计个数,右移后为奇数的个数及平均值。
通过审题可以发现仅有一个不同点,即参与平均值计算的元素是数组xx[i]右移一位之后为奇数的元素,参考答案的第9条语句。