获取Artihmetic异常错误

时间:2017-11-09 18:35:25

标签: c++ arithmetic-expressions

我写了这个程序。但是我得到了算术异常错误。 程序:

#include<bits/stdc++.h>
using namespace std;
int fact(int n)
{
    int facte = 1;
    for (int i = 1; i <= n; i++)
        facte *= i;
    return facte;
}
int main()
{
    int n, k;
    cin >> n >> k;
    int sum1 = 0;
    int res = 0;
    int temp = k;
    int term1, term2, term3;
    while ((n - temp) > 1)
    {
        term1 = fact(n);
        term2 = fact(n - temp);
        term3 = fact(temp);
        res = int((term1 / (term2 * term3)));
        sum1 += res;
        temp--;
    }

    cout << sum1 * fact(n - k - 1) + 1;
}

输入:      

n=4 and k=2
错误:    
 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

1 个答案:

答案 0 :(得分:0)

乘以两个阶乘数可以溢出int。

替换

 res = int((term1 / (term2 * term3)));

  res = (term1 / term2) / term3;

//添加括号只是为了确定 也改变了

 temp--;

temp++;