我从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 :(得分:0)
您可以使用字符串执行以下操作:
string line;
int yourNumber;
getline(cin, s);
//Cycle through the word and check for characters such as '@' which don't fit any of the specific error messages.
for (int i = 0; i < line.length(); i++){
if (line[i] != '-' || line[i] != '.' || !(line[i] >= '0' && line[i] <= '9'){
cout << "Generally invalid input such as 5sda2" << endl;
break;
}
}
//This line just checks if '-' exists in the string.
if (line.find('-') != std::string::npos)
cout << "No negatives" << endl;
else if (line.find('.') != std::string::npos)
cout << "No decimals" << endl;
else
yourNumber = std::stoi(line);
std :: stoi函数从std :: string转换为整数。它在
中定义#include <string> header
你还需要std :: string。如果你在使用getline之前使用cin,请务必调用cin.ignore以便克服缓冲区中留下的空白区域(When and why do I need to use cin.ignore() in C++?)。