自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