3ヶ月前からC++プログラミングを学びましたが、現在問題があります。別の条件を満たしたときにエラーメッセージを表示する方法
を調和するための式は、平均および幾何平均はあるが、Gであるのに対し
Hが調和平均であります幾何平均。
予想される出力を得るためにwhileループやdo-while-loopをif-else文と共に使用する方法はほとんど試していませんが、意図的に文字s、負の数または10進数などのプログラムを入力すると
はここ...次の操作の入力を再入力または更するかどうかを確認せずに、プログラムの最後にまっすぐに私を 向けられている私が作った私の最新のコードです:
#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;
}
ヘルプや変更がずっとここに感謝されます。
入力を文字列として受け取り、文字列内のすべての文字が数字(正の数)であることを確認してください。あなたが '0'が唯一の文字ではないことを確認する限り、あなたのコードを単純化し、後でintに変換することができます。 –
urm、期待されるチェックは次のようになります:inputがアルファベットの場合、 'only integer number'というエラーが表示されます。入力が負数またはゼロの場合、 'numberは0以上の整数でなければならない'というエラーが表示されます。 5.6や4.00などの小数点以下の桁が入力されている場合は、「小数点なし、整数のみ」というエラーが表示されます。正の整数であれば処理が進ま... .... – AetheneLockhart
トピックオフ: 'cin.ignore();'は、ユーザ入力エラーの後にクリーンアップするのに十分ではありません。それは1文字だけを無視し、誤った入力はそれ以上のものである可能性があります。 'cin.ignore(numeric_limits :: max()、 '\ n');'ユーザがenterを押すまで無視するか、入力ストリームをオーバーフローさせるのに十分長い時間入力します) –
user4581301