Advertisement
Guest User

Untitled

a guest
Nov 28th, 2015
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <iomanip>
  4.  
  5. #include <vector>
  6.  
  7. #include <cmath>
  8.  
  9. using namespace std;
  10.  
  11. double mean(vector <double> vec) {
  12.     double sum = 0;
  13.  
  14.     for (size_t i = 0; i < vec.size(); i++) {
  15.         sum += vec[i];
  16.     }
  17.  
  18.     return sum / vec.size();
  19. }
  20.  
  21. double read_vector(vector <double>& vec, char* filename) {
  22.     ifstream input(filename);
  23.     vec.clear();
  24.     double x;
  25.  
  26.     while (input >> x) {
  27.         vec.push_back(x);
  28.     }
  29. }
  30.  
  31. int main(int argc, char **argv) {
  32.     if (argc != 2) {
  33.         cout << "Usage: mean <filename>" << endl;
  34.         return 1;
  35.     }
  36.  
  37.     vector <double> vec;
  38.     read_vector(vec, argv[1]);
  39.  
  40.     if (vec.empty()) {
  41.         cout << "File should be non-empty!" << endl;
  42.         return 1;
  43.     }
  44.  
  45.     cout << setprecision(6) << fixed;
  46.     cout << mean(vec);
  47.    
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement