#include <iostream>
usingnamespace std;
int main(){
double n, var, sum=0, average;
cout << "Enter positive integer N: ";
cin >> n; var = n;
for (int x = 0; x <= var; x++)
{
sum = sum + n;
var = (var - 1.0);
average = sum / (n + 1.0);
while (cin.fail())
{
cin.clear();
cin.ignore();
cout << "Bad input. Try again.";
cin >> n;
}
}
if (n < 0) // Terminates Program if Input is Negative
{
return 0;
}
cout << "The mean of all integers from 0 to " << n
<< " is: " << average;
system("pause");
return 0;
}
#include <iostream>
#include <limits>
#include <cstdlib>
usingnamespace std;
int main(){
double n, var, sum = 0, average;
cout << "Enter positive integer N: " << flush;
while (!(cin >> n))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //ignores all characters until a newline
cout << "Bad input. Try again." << endl;
cout << "Enter positive integer N: " << flush;
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//exits program if a negative number is entered
if (n < 0)
{
cerr << "Negative numbers are not allowed program terminated" << flush;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
exit(EXIT_FAILURE);
}
var = n;
for (int x = 0; x <= var; x++)
{
sum = sum + n;
var = (var - 1.0);
average = sum / (n + 1.0);
}
cout << "The mean of all integers from 0 to " << n
<< " is: " << average;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return 0;
}