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

ID : 131382

viewed : 6

Tags : c++floating-pointc++

Top 5 Answer for Floating Point Exception C++ Why and what is it?

vote vote


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.

vote vote


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.

vote vote


Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.

for (i>0; i--;){ c= input%i; 

Thats division by zero at some point since you are decrementing i.

vote vote


Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.

vote vote


Problem is in the for loop in the code snippet:
for (i > 0; i--;)

Here, your intention seems to be entering the loop if (i > 0) and decrement the value of i by one after the completion of for loop.

Does it work like that? lets see.

Look at the for() loop syntax:

**for ( initialization; condition check; increment/decrement ) {       statements;   }** 

Initialization gets executed only once in the beginning of the loop. Pay close attention to ";" in your code snippet and map it with for loop syntax.

Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.

Condition check : i -- : post decrement.

              Here, i is used for condition check and then it is decremented.                Decremented value will be used in statements within for loop.                This condition check is working as increment/decrement too in your code.  

Lets stop here and see floating point exception.

what is it? One easy example is Divide by 0. Same is happening with your code.

When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.

Modulo operation at line #9 results in divide by zero operation.   

With this background you should be able to fix the problem in for loop.

Top 3 video Explaining Floating Point Exception C++ Why and what is it?