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?
You can run into computations that lead to division by zero when you are working on an array using a for loop. One of the best ways to do this is to check if the denominator is zero before you divide. This will avoid the floating-point exception error.
In C++ you declare them with float instead of int . A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero. Okay, well let me make sure I understand my own code before I try to fix it. The for lop will only execute if i > 0 right?
When a floating-point exception raises the SIGFPE signal, the process terminates and produces a core file if no signal-handler subroutine is present in the process. Otherwise, the process calls the signal-handler subroutine. Floating-point exception subroutines.
A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With