C++ 获取艺术异常错误
我写了这个程序。但我得到了算术异常错误。 节目:C++ 获取艺术异常错误,c++,arithmetic-expressions,C++,Arithmetic Expressions,我写了这个程序。但我得到了算术异常错误。 节目: #包括 使用名称空间std; 整数事实(整数n) { 内部因素=1; 对于(inti=1;i>n>>k; int sum1=0; int res=0; 内部温度=k; 国际术语1、术语2、术语3; 而((n-温度)>1) { term1=事实(n); term2=事实(n-温度); term3=事实(温度); res=int((第1条/(第2条*第3条)); sum1+=res; 温度--; } cout乘以两个阶乘数会溢出int 替换 res
#包括
使用名称空间std;
整数事实(整数n)
{
内部因素=1;
对于(inti=1;i>n>>k;
int sum1=0;
int res=0;
内部温度=k;
国际术语1、术语2、术语3;
而((n-温度)>1)
{
term1=事实(n);
term2=事实(n-温度);
term3=事实(温度);
res=int((第1条/(第2条*第3条));
sum1+=res;
温度--;
}
cout乘以两个阶乘数会溢出int
替换
res = int((term1 / (term2 * term3)));
与
//添加括号只是为了确定
也改变
temp--;
到
term2
或term3
必须为零。dop term2
和p term3
要查看它们的值,我认为应该是sum1+=res;
代替sum+=res;
term1,term2,term3不能为零,因为事实函数将返回值>=1@AlgirdasPreidžius我想有一些因素计算nt variables溢出。因此建议不要乘以两个大数字。这是假设阶乘本身没有溢出。对。但如果它们溢出,则会更早引发异常。在这种情况下,使用long int或其他合适的类型。我只给出n=4和k=2,不一定是大值。事实
可能是“在未定义的行为中发现了很长一段时间而未被发现。@AdilMahmood编辑您的问题并将这些输入添加到其中。
GDB trace:
Reading symbols from solution...done.
[New LWP 18123]
Core was generated by `solution'.
Program terminated with signal SIGFPE, Arithmetic exception.
#0 main () at solution.cc:29
29 res=int((term1/(term2*term3)));
#0 main () at solution.cc:29
res = int((term1 / (term2 * term3)));
res = (term1 / term2) / term3;
temp--;
temp++;