使用visual studio 2019写如下代码时
#include <iostream>
using namespace std;
int func1(int n);
int main()
{
int number;
cin >> number;
try { cout << func1(number) << endl; }
catch ( char* e)
{
cout << e << endl;
return 1;
}
}
int func1(int n)
{
int res = 1;
if (n < 0)
throw "error: n <0";
if (n == 0 || n == 1)
return 1;
while (n > 1)
{
res *= n;
n--;
}
return res;
}
理论上当n<0时,应为溢出计算范围,会抛出一个异常,但是产生如图错误
将代码改成如下,问题得以解决;
#include <iostream>
using namespace std;
int func1(int n);
int main()
{
int number;
cin >> number;
try { cout << func1(number) << endl; }
catch (const char* e)
{
cout << e << endl;
return 1;
}
}
int func1(int n)
{
int res = 1;
if (n < 0)
throw "error: n <0";
if (n == 0 || n == 1)
return 1;
while (n > 1)
{
res *= n;
n--;
}
return res;
}
网友评论