简体   繁体   English

为什么我的SPOJ GCD2代码在SPOJ上出错?

[英]Why does my code for SPOJ GCD2 error on SPOJ?

Following is code for SPOJ GCD2 . 以下是SPOJ GCD2的代码。 It's running well on my machine and Ideone, but getting runtime error (SIGFPE) on SPOJ. 它在我的机器和Ideone上运行良好,但是在SPOJ上出现运行时错误(SIGFPE)。 I have checked all the test cases also available at spojtoolkit.com. 我已经检查了spojtoolkit.com上所有可用的测试用例。

I am unable to figure out why this code is showing runtime error (SIGFPE) on spoj. 我无法弄清楚为什么此代码在spoj上显示运行时错误(SIGFPE)。 SIGFPE means Erroneous arithmetic operation. SIGFPE表示错误的算术运算。

Why is this code showing runtime error on SPOJ? 为什么此代码在SPOJ上显示运行时错误?

#include <bits/stdc++.h>

using namespace std;

int gcd(int x,int a)
{
    if(a==0)
        return x;
    else
        return gcd(a, x%a);
}


int getmod(string b,int a)
{
    int n=b.size();
    int d;
    d= (b[0]-'0') % a;
    for(int i=1; i!=n; i++)
    {
        d=d*10;
        d=d + (b[i]-'0');
        d= d % a;
    }
    return d;

}
int main()
{
    int tc;
    cin >> tc;
    int a;
    string b;
    while(tc--)
    {
        cin >>a>>b;
        int x=getmod(b,a);
        cout << gcd(x,a)<<endl;

    }
    return 0;
}
int getmod(string b,int a)
{
    int n=b.size();
    int d;
    d= (b[0]-'0') % a;

If a = 0 , this will error, because % 0 is like dividing by zero. 如果a = 0 ,这将出错,因为% 0就像被零除。 a can be zero according to the problem statement. 根据问题陈述, a可以为零。

The error covers division by zero : 该错误包括被零除

The SIGFPE signal reports a fatal arithmetic error. SIGFPE信号报告致命的算术错误。 Although the name is derived from “floating-point exception”, this signal actually covers all arithmetic errors, including division by zero and overflow. 尽管名称源自“浮点异常”,但该信号实际上涵盖了所有算术错误,包括零除和溢出。 If a program stores integer data in a location which is then used in a floating-point operation, this often causes an “invalid operation” exception, because the processor cannot recognize the data as a floating-point number. 如果程序将整数数据存储在随后用于浮点运算的位置,则这通常会导致“无效运算”异常,因为处理器无法将数据识别为浮点数。

You can fix it by checking if a == 0 and simply returning b as the answer in that case. 您可以通过检查a == 0并在这种情况下简单地返回b作为答案来修复它。 Else call your current function as is. 否则按原样调用您当前的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM