I am trying to return a list of mean values. Something like this:
Mean of the first 1 element(s): 1
Mean of the first 2 element(s): 3
Mean of the first 3 element(s): 4
Mean of the first 4 element(s): 5
#include <iostream>
#include <math.h>
#include <iomanip>
#include <vector>
#include <numeric>
usingnamespace std;
int valid(int);
vector<int> numbers;
int main()
{
int i, x;
cout << "Please enter a positive integer and '-1' to exit: ";
cin >> i;
while (i>=1)
{
valid(i);
cout << "Please enter a positive integer and '-1' to exit: ";
cin >> i;
if (i == -1)
{
break;
}
}
while (i<1)
{
if (i == -1)
{
for (x=0; x<numbers.size(); x++)
{
cout << "numbers[" << x << "] = " << numbers[x] << "\n";
}
break;
}
cout << "That is not a valid number! Please try again.\nPlease enter a positive integer and '-1' to exit: ";
cin >> i;
while (i>=1)
{
valid(i);
cout << "Please enter a positive integer and '-1' to exit: ";
cin >> i;
if (i == -1)
{
for (x=0; x<numbers.size(); x++)
{
cout << "numbers[" << x << "] = " << numbers[x] << "\n";
}
break;
}
}
}
}
int valid(int a)
{
numbers.push_back(a);
double mean = accumulate( numbers.begin(), numbers.end(), 0.0) /numbers.size();
if (static_cast<int>(mean)==mean)
{
cout << "The new arithmetic mean is " << mean << "\n" << "Your input has been accepted!\n";
}
else
{
cout << "Sorry, your input was rejected and will be removed!\n";
numbers.pop_back();
}
}
#include <iostream>
#include <vector>
int get_int()
{
std::cout << "Please enter a positive integer or '-1' to exit: " ;
int n ;
if( std::cin >> n && ( n > 0 || n == -1 ) ) return n ;
std::cout << "invalid input. try again\n" ;
std::cin.clear() ; // clear the (possible) failed state of std::cin
std::cin.ignore( 1000, '\n' ) ; // throw away the rest of the input line
return get_int() ; // and try again
}
int main()
{
std::vector<int> numbers ;
longlong total = 0 ; // running total
int n ;
while( ( n = get_int() ) != -1 )
{
total += n ;
numbers.push_back(n) ;
std::cout << "mean of the " << numbers.size() << " numbers [ " ;
for( int v : numbers ) std::cout << v << ' ' ;
std::cout << " ] is " << double(total) / numbers.size() << '\n' ;
}
}