Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating point exception [duplicate]

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?

like image 258
Shelith Avatar asked Sep 01 '10 06:09

Shelith


People also ask

How do you fix a floating point exception?

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.

How do you fix a floating point exception in CPP?

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?

What is floating point exception Sigfpe?

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.

What is floating point exception core dumped?

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.


1 Answers

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:

  1. Try to format your code better. Focus on using a consistent style. E.g. you have one else that starts immediately after a if brace (not even a space), and another with a newline in between.
  2. Don't use globals unless necessary. There is no reason for q to be global.
  3. Don't return without a value in a non-void (int) function.
like image 170
Matthew Flaschen Avatar answered Sep 21 '22 16:09

Matthew Flaschen