I learnt C++ programming since 3 months ago and currently met some problem.
This is the expected output that I was being assigned to expect the output:
While the formula for the Harmonic mean and Geometric mean are:
H is harmonic mean while G is geometric mean.
I tried few ways using while-loop or do-while-loop together with the if-else statement to achieve the expecting output but whenever i purposely input the wrong such as letter s, negative number or decimal number, the program is directed me straight to the end of the program, without asking to retype or further input for next operation...
here is my latest code i made:
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
int main()
{
double H, G, n, f, x;
long double HX = 0, GX = 1;
double TypeIn[1000] = {};
cout << "How many values to type?: ";
cin >> n;
while (!(n > 0) && (n == static_cast <int> (n)) && !(cin >> n));
{
if (n != static_cast <int> (n))
{
cout << "No decimal number please: ";
cin >> n;
}
else if (!(cin >> n))
{
cin.clear();
cin.ignore();
cout << "INTEGER number ONLY: ";
cin >> n;
}
else if (n <= 0)
{
cout << "the number must be integer number more than 0, please retype: ";
cin >> n;
}
}
for (int k = 0; k < n; k++)
{
cout << "Enter number #" << k + 1 << ": ";
cin >> x;
while (!(x > 0) && (x == static_cast <int> (x)) && !(cin >> x));
{
if (x != static_cast <int> (x))
{
cout << "No decimal number please: ";
cin >> x;
}
else if (!(cin >> x))
{
cin.clear();
cin.ignore();
cout << "INTEGER number ONLY: ";
cin >> x;
}
else if (x <= 0)
{
cout << "the number must be integer number more than 0, please retype: ";
cin >> x;
}
}
TypeIn[k] = x;
HX += 1 / TypeIn[k];
GX *= TypeIn[k];
}
H = n / HX;
f = 1 / n;
G = pow(GX, f);
cout << "\nFor data:";
for (int k = 0; k < n; k++)
{
cout << TypeIn[k];
}
cout << setprecision(5);
cout << "\n\nThe harmonic mean is " << H << endl;
cout << "The geometric mean is " << G << endl;
system("pause");
return 0;
}
Help and change is much appreciated here.