【发布时间】:2016-12-23 00:25:08
【问题描述】:
我从 3 个月前开始学习 C++ 编程,目前遇到了一些问题。
H 是调和平均,而 G 是几何平均。
我尝试了几种使用 while-loop 或 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,预期的检查是这样的:如果输入是任何字母,则会显示'only integer number'的错误;如果输入为负数或零,将显示“数字必须是大于0的整数”的错误;如果输入是小数位,如 5.6 或 4.00,则会显示“没有小数位,只有整数”的错误......只有当它是一个正整数时才会继续......
-
离题:
cin.ignore();不足以在用户输入错误后进行清理。它只忽略一个字符,错误的输入可能远不止于此。cin.ignore(numeric_limits<streamsize>::max(), '\n');应该通过忽略直到用户按下回车键(或者用户输入足够长的时间以溢出输入流)来覆盖它
标签: c++ if-statement for-loop while-loop do-while