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