📄 28.cpp
字号:
/*先创建文本文件IN.DAT,在文件中写20个四位整数。
编写函数readDat()把从文件中读出这些数并存入数组a中;编写函数Calvalue( ), 其功能要求:
1. 求出这文件中共有多少个正整数totNum;
2. 求这些数右移1位后, 产生的新数是偶数的数的个数totCnt, 以及满足此条件的这些数(右移前的值)
的算术平均值totPjz。
最后在main( )函数中把所求的结果输出。*/
#include <stdio.h>
#include <conio.h>
#define N 20
int a[N];
int totNum=0;
int totCnt=0;
double totPjz=0.0;
int ReadDat(void);
void CalValue(void)
{
int i,K;
for(i=0;i<N;i++)
if(a[i]>0)
{
totNum++;
K=a[i]>>1;
if(K%2==0)
{
totCnt++;totPjz+=a[i];
}
}
if(totCnt==0)
totPjz=0;
else
totPjz=totPjz/totCnt;
}
void main()
{
int i;
for(i=0;i<N;i++)
a[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);
}
int ReadDat(void)
{
FILE *fp;
int i=0;
if((fp=fopen("IN.DAT","r"))==NULL)
return 1;
while(!feof(fp))
{
fscanf(fp,"%d,",&a[i++]);
}
fclose(fp);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -