Why do I got a SIGFPE, Arithmetic exception error when I'm using a modulo on an int obtained by a modulo of a different integer in my code?

Viewed 388

I'm trying to solve a problem in hackerrank but I got a SIGFPE, Arithmetic exception error when I tried to compile my code. After a few trial and errors, I figured out that the problem lies between the part which I wrote "if(y%m==0)" because the m variable apparently contain an integer which was obtained by a modulo operation of another integer. Can somebody please explain to me why this happened and how to fix it? Here are my codes that I wrote :

#include <stdio.h>

int main()
{
    int x,y,z,m,total;
    scanf("%d", &x);
    for(int i = 0; i<x; i++)
    {
        scanf("%d", &y);
        for(z=y; z>0;z/=10)
        {
            if(z==y)
            total = 0;
            m=(z%10);
            if(y%m==0)
            {
                total++;
            }
        }
        printf("\n%d\n", total);
    }
}
1 Answers

If the user enters a y value that's divisible by 10, then z will also be divisible by 10. Then, when you set m=(z%10);, m is set to 0. Doing y % m in such a situation is a division by 0 error.

Maybe consider first checking to make sure m isn't 0?

if(m == 0 || y%m==0)
{
  total++;
}

Demo

Related