daily pastebin goal
93%
SHARE
TWEET

Untitled

a guest Jan 18th, 2019 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <cstdlib>
  5. #include <fstream>
  6. #include <sstream>
  7. #include <iomanip>
  8. using namespace  std;
  9.  
  10. void readFile(string filename, vector<double> &finals);
  11. double average(const vector<double> &finals);
  12. double median(vector<double> finals);
  13. void display(const vector<double> &finals, double avg, double median);
  14. int main()
  15. {
  16. string filename;
  17. vector<double> final_scores;
  18. double avg, med;
  19. cout << "Enter input filename: ";
  20. cin >> filename;
  21. readFile(filename, final_scores);
  22. avg = average(final_scores);
  23. med = median(final_scores);
  24. display(final_scores, avg, med);
  25. }
  26.  
  27. void readFile(string filename, vector<double> &finals)
  28. {
  29. ifstream infile(filename.c_str());
  30. if(infile.fail())
  31. {
  32. cout << "ERROR: could not open input file " << filename << endl;
  33. exit(1);
  34. }
  35. string line;
  36. double avg, score;
  37. int n;
  38. while(getline(infile, line)) //get the line of scores for a student
  39. {
  40. avg = 0;
  41. n = 0;
  42. stringstream lstream(line);
  43. while(lstream >> score) //calculate average of scores for a single student and push the average into finals
  44. {
  45. avg += score;
  46. n++;
  47. }
  48. avg /= n;
  49. finals.push_back(avg);
  50. }
  51. infile.close();
  52. }
  53. double average(const vector<double> &finals)
  54. {
  55. double avg = 0;
  56. for(int i = 0; i < finals.size(); i++)
  57. avg += finals[i];
  58. avg /= finals.size();
  59. return avg;
  60. }
  61. double median(vector<double> finals)
  62. {
  63. double median;
  64. int mid = finals.size() / 2;
  65. sort(finals.begin(), finals.end());
  66. if(finals.size() % 2 == 1) //odd length
  67. median = finals[mid];
  68. else
  69. median = (finals[mid] + finals[mid-1])/2; //average of middle 2 values
  70. return median;
  71. }
  72. void display(const vector<double> &finals, double avg, double median)
  73. {
  74. cout << "The scores for the students is" << endl;
  75. cout << fixed << setprecision(2);
  76. for(int i =0; i < finals.size(); i++)
  77. {
  78. cout << (i+1) << ". " << finals[i] << endl;
  79. }
  80. cout << endl << "The average score is " << avg << endl;
  81. cout << "The median score is " << median << endl;
  82. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top