简体   繁体   中英

How can I solve this median programming problem in C++

  1. Formulate the steps of identifying the median from five unique numbers and visualize them in flow chart.
  2. Develop an application that shows the median after getting five unique numbers from users.
  3. Extend the feature for allowing six unique numbers input and computing the median.

Example:
Input: 5 4 2 1 10
Output: Median = 4

I found this question in a Problem Solving with C++ by Walter Savitch but I couldn't solve it. Can anyone explain it to me?

Trying to give homework-friendly advice:

1) Make sure you know how to get a Median . Can you, in your head or on paper, figure it out? Now, how do you write a program to do this for you? Make a flowchart .

2) Write the program to do it. A user gives your program 5 numbers, your program gives the median as an answer.

3) Make the program better. An even amount of numbers changes the method to get a median. Change your program so that it will allow 6 numbers.

3b) Make your program accept any amount of numbers. (I added this, not in your post or in your book but should be super-easy to do if you've already done 2 and 3).

Can anyone explain it to me?

  1. "Formulate the steps" means, "explain how to do it". For example, imagine that you're explaining to me how to solve the problem, that I don't need to use a computer (that I'm trying to do it with pencil and paper), and that I don't know what a "median" is.

  2. "Develop an application" means, "write software". The software will need to: a) get five numbers from the user (and, possibly, ensure that the numbers are "unique"); b) find the "median" (using the steps you've previously formulated in step 1); c) show (output) the median which it found.

  3. You'll need to define what "median" means when there's an even number of inputs, and alter your program accordingly.

I know no one asked for an answer using STL, but it could be useful for someone coming here later.

In C++ with STL there is a function called nth_element , which takes three arguments. It will sort a container just enough to get nth element in the right spot.

An example:

int numbers[] = { 5, 4, 2, 1, 10 };
std::nth_element(numbers, numbers+2, numbers+5);
std::cout << numbers[2] << "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM