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);
}
}
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++;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.