1
do
{
cout << "Enter the numerator and denominator of the first fraction: ";
cin >> a >> b;
cout << endl;
cout << "Enter the numerator and denominator of the second fraction: ";
cin >> c >> d;
cout << endl;
} while (!validNum(a, b, c, d));
...
bool validNum(int num1, int num2, int num3, int num4)
{
if (cin.fail() || num2 == 0 || num4 == 0)
{
if (num2 == 0 || num4 == 0)
{
cout << "Invalid Denominator. Cannot divide by 0" << endl;
cout << "try again: " << endl;
return false;
}
else
{
cout << "Did not enter a proper number" << endl;
cout << "try again: " << endl;
return false;
}
}
else
return true;
}
我想要做的是确保分母不为零,并且他们只输入数字。除零代码的工作正常,但是当你输入一个char值时,它会进入一个无限循环,不知道为什么。有任何想法吗?无效int输入陷入无限循环
真棒它的作品完美。出于好奇,numeric_limits :: max()是如何工作的以及它做了什么 –
@JuanSierra ['numeric_limits :: max'](http://en.cppreference.com/w/cpp/types/numeric_limits/max)返回给定类型的最大值。 – 0x499602D2