Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Floating Point Exception C++ Why and what is it?

I'm building a program for the Euler projects question 3, and while that might not really matter as a result I'm current trying to make this code take a number and test if it is prime or not. Now then before I get to troubleshoot the function it gives me the error "floating point exception" right after inputting the number. Here's the code:

int main() {     int input;     cout << "Enter number: " << endl;     cin>> input;     int i = input/2;     int c;     for (i>0; i--;) {         c= input%i;         if (c==0 || i == 1)             cout << "not prime" << endl;         else             cout << "prime" << endl;     }     return 0; } 

so essentially why is it giving me a floating point exception and what does that even mean?

like image 538
samuraiseoul Avatar asked Nov 21 '10 07:11

samuraiseoul


People also ask

What is floating-point in C programming?

A "floating-point constant" is a decimal number that represents a signed real number. The representation of a signed real number includes an integer portion, a fractional portion, and an exponent. Use floating-point constants to represent floating-point values that can't be changed.

Why does floating error occur?

It's a problem caused when the internal representation of floating-point numbers, which uses a fixed number of binary digits to represent a decimal number. It is difficult to represent some decimal number in binary, so in many cases, it leads to small roundoff errors.

What is floating-point exception core dumped?

This answer is useful. This answer is not useful. Show activity on this post. Floating Point Exception happens because of an unexpected infinity or NaN. You can track that using gdb, which allows you to see what is going on inside your C program while it runs.


2 Answers

A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. 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.

like image 123
Crashworks Avatar answered Oct 11 '22 18:10

Crashworks


for (i>0; i--;) 

is probably wrong and should be

for (; i>0; i--) 

instead. Note where I put the semicolons. The condition goes in the middle, not at the start.

like image 20
fredoverflow Avatar answered Oct 11 '22 17:10

fredoverflow