#include<stdio.h>
main()
{
FILE *open; /*说明文件指针变量open */
int x,sum,aver,n;
if((open=fopen("30.cpp","r"))==NULL)
printf("打开文件失败.\n");
return;
}
sum=0;
n=0;
while(fscanf(open,"%d",&x)!=-1)
{
sum=sum+x;
n++;
}
fclose(open);
aver=sum/n;
printf("aver=%d\n",aver);
}
修改如下,供参考:
#include<stdio.h>
int main()
{
FILE *open; /*说明文件指针变量open */
int x,sum,aver=0,n;
if((open=fopen("30.txt","r"))==NULL){ //if((open=fopen("30.cpp","r"))==NULL)
printf("打开文件失败.\n");
return -1;
}
sum=0;
n=0;
while(fscanf(open,"%d",&x)== 1) //while(fscanf(open,"%d",&x)!=-1)
{
sum=sum+x;
n++;
}
fclose(open);
if(n != 0) aver=sum/n; //修改
printf("aver=%d\n",aver);
return 0;
}
while(fscanf(open,"%d",&x)&&x!=-1)
#include<stdio.h>
main()
{
FILE *open; /*说明文件指针变量open */
int x,sum,aver=0,n;
if((open=fopen("30.txt","r"))==NULL) /*打开文件失败*/
{
printf("打开文件失败.\n");
return -1; /*终止程序*/
}
sum=0;
n=0;
while(fscanf(open,"%d",&x)==1)
{
sum=sum+x;
n++;
}
fclose(open);
if(n!=0)
aver=sum/n;
printf("aver=%d\n",aver);
return 0;
}