自3個月前我學習了C++編程,目前遇到了一些問題。如何在遇到不同條件時顯示錯誤消息
H是調和平均數,而G是幾何平均數。
我嘗試了幾種使用while循環或do-while-loop與if-else語句一起實現預期輸出的方法,但是每當我故意輸入錯誤的字母s,負數或小數,程序針對我直接到節目結束,而不要求重新輸入或接下來的操作進一步輸入...
這是我最新的代碼我提出:
#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,預期的檢查是這樣的:如果輸入是任何字母,它將顯示'只有整數'的錯誤;如果輸入是負數或零,它將顯示'數字必須是0以上的整數'的錯誤;如果輸入的是小數位,如5.6或4.00,它將顯示'無小數位,只有整數'的錯誤.......只有當它是一個正整數時,纔會繼續... – AetheneLockhart
Off topic :'cin.ignore();'不足以在用戶輸入錯誤後清理。它只會忽略一個字符,錯誤的輸入可能遠不止於此。 ''cin.ignore(numeric_limits :: max(),'\ n');'應該覆蓋,直到用戶按下回車鍵(或者用戶類型足夠長才能溢出輸入流) –
user4581301