Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In c++ If we define the median of a sequence as “a number so that exactly as man

ID: 3752758 • Letter: I

Question

In c++

If we define the median of a sequence as “a number so that exactly as many elements come before it in the sequence as come after it,” fix the program in §4.6.3 so that it always prints out a median. Hint: A median need not be an element of the sequence.

§4.6.3:

// compute mean and median temperatures

int main() {

vector temps; // temperatures

for (double temp; cin>>temp; ) // read into temp

temps.push_back(temp); // put temp into vector

// compute mean temperature:

double sum = 0;

for (int x : temps) sum += x;

cout << "Average temperature: " << sum/temps.size() << ' ';

// compute median temperature:

sort(temps); // sort temperatures

cout << "Median temperature: " << temps[temps.size()/2] << ' ';

}

Explanation / Answer

#include <iostream>

#include<vector>

#include<algorithm>

using namespace std;

// compute mean and median temperatures

int main() {

vector<double> temps; // temperatures

for (double temp; cin>>temp; ) // read into temp

temps.push_back(temp); // put temp into vector

// compute mean temperature:

double sum = 0;

for (int x : temps) sum += x;

cout << "Average temperature: " << sum/temps.size() << ' ';

// compute median temperature:

sort(temps.begin(),temps.end()); // sort temperatures

// median of even numbers is always considered as average of middle two elements

if(temps.size()%2==1)

cout << "Median temperature: " << temps[temps.size()/2] << ' ';

else

cout << "Median temperature: " << (temps[temps.size()/2]+temps[(temps.size()/2)-1])/2 << ' ';

}

/*sample output

*/

As per the given for loop syntax you need to enter a character to exit the user input loop

small modifications has been done to the program as per the c++ standards. please observe those

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote