gpt4 book ai didi

c++ - 无效的 int 输入陷入无限循环

转载 作者:行者123 更新时间:2023-11-30 04:13:12 27 4
gpt4 key购买 nike

<分区>

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 值时,它会进入无限循环并且不知道为什么。有什么想法吗?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com