Hi yall! I've been working on a problem that takes all the numbers that have been entered into a vector, takes the mean of them, and then outputs all the numbers entered into the vector that are smaller than the mean. I am really confused on how to output the numbers below the mean that are put into the vector. Any suggestions?? Thanks!
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<vector>
#include<bits/stdc++.h>
using namespace std;
int main(){
vector <float> number;
float userinput;
float sum = 0;
float mean = 0;
cout << " Enter a string of numbers and I will calculate the mean." << endl;
while(true){
cin >> userinput;
if(userinput == -1){
break;
}
else{
number.push_back(userinput);
}
}
sort(number.begin(), number.end());
for(int i = 0; i < number.size(); i++){
sum += number[i];
}
mean = sum/number.size();
cout << mean << endl;
for(int x = 0; x < mean; x++){
cout << number[x];
cout << " ";
}
}
for(int x = 0; x < mean; x++){
cout << number[x];
cout << " ";
This block has faulty logic. If the mean were 5000 then it would try to print 5000 elements but your vector 'numbers' need not have that many elements.
You could get that block to work if you calculated the median's index and assigned it to mean.
But in my opinion that's not necessary.
Instead don't worry about having to sort. Calculate the mean and then the last for-loop block should be:
1 2 3 4 5
for(int x = 0; x < numbers.size(); x++){
if(numbers[x] < mean) {
cout << number[x];
cout << " ";
}
#include<iostream>
#include<vector>
int main() {
std::vector<double> numbers ;
std::cout << "Enter a sequence of numbers and I will calculate the mean\n"
<< "enter any non-numeric string (eg. END) to end input.\n" ;
// note: avoid having to compare floating point values for equality
double input ;
while( std::cin >> input ) numbers.push_back(input) ;
if( !numbers.empty() ) { // if at least one number was entered
// compute the sum of all the numbers
double sum = 0 ;
// http://www.stroustrup.com/C++11FAQ.html#forfor( double v : numbers ) sum += v ; // add each number in the vector to sum
constdouble mean = sum / numbers.size() ; // determine the mean
std::cout << "mean: " << mean << '\n' ;
std::cout << "numbers which are smaller than the mean are: " ;
for( double v : numbers ) // for each number in the vector
if( v < mean ) std::cout << v << ' ' ; // print it if it is smaller than the mean
std::cout << '\n' ;
}
}
Note that while using JLBorges example, because of while( std::cin >> input ) you need to end input with a NULL character. So if you're using keyboard you need to use the appropriate shortcut keys.