C++求平均值

来源:百度知道 编辑:UC知道 时间:2024/07/07 08:26:56
大家帮帮给给参考程序
Description:输入一些正整数(每个正整数≤1000000,整数个数不大于1000),求所有这些正整数的平均值。平均值保留两位小数。
Input:123 321 3 2 1 6 3
Output:65.57

#include <iostream>
using namespace std;
int main()
{
int n = 0;
long total = 0;
long tmp = 0;
while( cin>>tmp )
{
total += tmp;
++n;
}
printf("%0.2f",(float)total/n);

return 0;
}
123
321
3
2
1
6
3
^Z
65.57请按任意键继续. . .

以ctrl+z结束输入,Linux下好像是Ctrl+D.

如果是读文件的话只需要把cin替换成这个就可以了:
ifstream ifs("input.txt");
//确保ifs成功
if( ifs.fail())
return -1;

记得最后关闭文件:
ifs.close();

#include <stdio.h>

void main()
{
long n,m,cnt=0,sum=0;

puts("输入正整数个数:");
scanf("%d",&m);
puts("输入一些正整数:");
while(cnt<m)
{
scanf("%d",&n);
if(n<1000000 & cnt<1000)
{
sum+=n;
cnt++;
}
else
{
break;
}
}
printf