-
vectors
I am supposed write a program that allows the user to enter
a set of positive integers in order from smallest to largest and then
the program will output the median of the set of numbers. The user
will type a -5 to indicate that the list of integers is complete. (The -5
is not part of the list).
If the user doesn't enter the numbers in order, the program should
display "Numbers entered out of order. Exiting." and exit. You can exit the
program using the command: exit(1)
I am supposed to write this program using vectors.
My problem is that I can't seem to figure out in my head how to run a loop for this.
I keep getting errors but here is my program so far. Can someone give me some advice?
I am very new at this and I think it has something to do with how I am asking the user to input things but I am not sure.
Code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> theNumbers;
cout << "Enter a set of positive integer from least to greatest." << endl;
cout << "When you are done, press '-5' to evaluate the median." << endl;
int i;
while (i>0)
{
cin >> i;
theNumbers.push_back(i);
if ( i < i-1)
{
cout << "Numbers entered out of order. Exiting." << endl;
exit(1);
}
}
int theMedian;
theMedian = (theNumbers.size() -1) /2 ;
cout << "The median is: " << theMedian << endl;
return 0;
}
-
your input should be inside the loop
so I think somethink like this:
Code:
while(cin>>i)
{
if(i == -5)
break; /* end input indication */
...
should be suitable
-
Note that using "exit" is almost never a good idea. It will instantly terminate the program, not allowing for cleanup or recovery or the like.
-
Code:
theNumbers.push_back(i);
if ( i < i-1)
{
cout << "Numbers entered out of order. Exiting." << endl;
exit(1);
}
That should be something more like:
Code:
if( theNumbers.size() && i < theNumbers[theNumbers.size()-1] )
{
cout << "Numbers entered out of order. Exiting." << endl;
exit(1);
}
theNumbers.push_back(i);
Code:
int theMedian;
theMedian = (theNumbers.size() -1) /2 ;
That does not calculate the median value but rather calculates the number of items in the vector (minus 1) divided by two. You're looking for something closer to the value at that index, not the index itself. The statistical median value of a set with odd number of elements is the middle value. The median value of a set with an even number of
elements is the average of the two middle-most values.
...and you probably should have just continued posting on the other thread instead of creating a new one.