I successfully complied this code:
#include <stdio.h>
#include <math.h>
int q;
int main()
{
srand( time(NULL) );
int n=3;
q=ceil(sqrt(n));
printf("%d\n %d\n", n,q);
if(n == 2)
printf("%d\n is prime", n);
else if(n % 2 == 0.0 || n < 2)
printf("%d\n is not prime", n);
else
{
int x;
for(x = 0; x < q; x++){
if(n % x == 0)
{
printf("%d\n is not prime", n);
return;
}
else
printf("%d\n is prime", n);
}
}
}
But when I run my code I get the following error:
Floating point exception
What does this error mean and how can I fix it?
This question is related to
c
floating-point
It's caused by n % x
where x = 0
in the first loop iteration. You can't calculate a modulus with respect to 0.
It's caused by n % x
, when x
is 0. You should have x start at 2 instead. You should not use floating point here at all, since you only need integer operations.
General notes:
q
to be global.http://en.wikipedia.org/wiki/Division_by_zero
http://en.wikipedia.org/wiki/Unix_signal#SIGFPE
This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0
IS division by zero and as such, will trigger a SIGFPE being thrown.
Source: Stackoverflow.com