C++编程练习-求平均年龄


Description
班上有学生若干名,给出每名学生的年龄(整数),求班上所有学生的平均年龄,保留到小数点后两位。
Input
第一行有一个整数n(1<= n <= 100),表示学生的人数。其后n行每行有1个整数,取值为15到25。
Output
输出一行,该行包含一个浮点数,为要求的平均年龄,保留到小数点后两位。
Sample Input
2
18
17
Sample Output
17.50Hint
要输出浮点数、双精度数小数点后2位数字,可以用下面这种形式:

printf("%.2f", num);

参考代码

  1. #include <iostream>   
  2. #include <iomanip>   
  3. using namespace std;  
  4. int main(){  
  5.     int n,i;  
  6.     float s,age;  
  7.     std::cin>>n;  
  8.     s = 0;  
  9.     for(i = 0;i < n;i ++){  
  10.         std::cin>>age;  
  11.         s += age;  
  12.     }  
  13.     std::cout<<std::fixed<<std::setprecision(2)<<s / n<<std::endl;  
  14.     return 0;  
  15. }  

相关内容