【问题标题】:Runtime Error - SIGFPE运行时错误 - SIGFPE
【发布时间】:2016-08-28 08:42:59
【问题描述】:

我有以下代码用于hackerearth 竞赛并用 C++ (g++ 4.8.4) 编写 它在运行时提供 SIGFPE 我刚刚完成了它

请告诉如何修复它

    #include<iostream>
    using namespace std;
    int factorial(int n);
   int main()
  {
   int n , k ,totitem , totways=0 , har1,har2, ansh=1;
int res;
cin>>n>>k;
totitem = (n/k);

ansh=factorial(n);

if(totitem>0)
for(int i=0;i<=totitem*k;i+=k)
{
    har1=factorial(i);
    har2=factorial(n-i);
    totways+=(ansh/(har1*har2));
}

cout<<totways;

return 0;
}
int factorial(int n)
{
if(n>1)
 return n*factorial(n-1);
 else
// if(n==0 || n==1)
 return 1;
}

【问题讨论】:

    标签: c++ runtime-error sigfpe


    【解决方案1】:

    通常是除以零错误。

    您的代码中有两个除法语句。

    1:

    totitem = (n/k);
    

    您不清理输入的地方。

    2:

    har1=factorial(i);
    har2=factorial(n-i);
    totways+=(ansh/(har1*har2));
    

    如果任何 har 参数等于 0,这将失败。

    问题的最可能原因是您正在使用 32 位有符号整数 (int) 进行阶乘计算,其阶乘限制为 12!尝试对较大的数字进行阶乘会导致溢出,从而导致结果不正确并最终为零值,从而导致运行时错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      相关资源
      最近更新 更多