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

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?

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.

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.

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.

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.

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.

Related

Why is the "if" not executed within a loop?

The cout << "Fin", it is never executed
int main(){
int num, suma=0, divisor=0;
cout<<"Escribe un nĂºmero"<<endl;
cin>>num;
cout<<num<<": ";
while(divisor<num){
if(num % divisor==0){
cout<<divisor;
}
}
cout<<"Fin";
num % divisor with divisor=0 does division by zero, which typically leads to aborting.
You should give another initial value (maybe 1 or 2 looks good, depending on the purpose) to that.
Also, as #KfirVentura pointed out, you should update divisor (or num) in the loop, or the loop will run infinitely if divisor<num initially becomes true.
"if" loop would not run as divisor is 0 and for all conditions will give a runtime exception error, which is apparent. Try changing the value of divisor.

Prevent a user from entering a value which would cause integer to overflow

I'm very new to C++ programming, and have written a simple program to calculate the factorial of an integer provided by the user. I am attempting to account for inputs which would cause an error, or do not make sense (e.g. I have accounted for input of a negative number/-1 already). I want to print out an error if the user enters a number whose factorial would be larger than the maximum integer size.
I started with:
if(factorial(n) > INT_MAX)
std::cout << "nope";
continue
I tested this with n = ~25 or 26 but it doesn't prevent the result from overflowing and printing out a large negative number instead.
Second, I tried assigning this to a variable using a function from the 'limits.h' header and then comparing the result of factorial(n) against this. Still no luck (you can see this solution in the code sample below).
I could of course assign the result to a long and test against that but you wouldn't have to go very far until you started to wrap around that value, either. I'd prefer to find a way to simply prevent the value from being printed if this happens.
#include <iostream>
#include <cstdlib>
#include <limits>
int factorial(int n)
{
auto total = 1;
for(auto i = 1; i <= n; i++)
{
total = total * i; //Product of all numbers up to n
}
return total;
}
int main()
{
auto input_toggle = true;
auto n = 0;
auto int_max_size = std::numeric_limits<int>::max();
while(input_toggle = true)
{
/* get user input, check it is an integer */
if (factorial(n) > int_max_size)
{
std::cout << "Error - Sorry, factorial of " << n << " is larger than \nthe maximum integer size supported by this system. " << std::endl;
continue;
}
/* else std::cout << factorial(n) << std::endl; */`
As with my other condition(s), I expect it to simply print out that small error message and then continue asking the user for input to calculate. The code does work, it just continues to print values that have wrapped around if I request the factorial of a value >25 or so. I feel this kind of error-checking will be quite useful.
Thanks!
You are trying to do things backwards.
First, no integer can actually be bigger than INT_MAX, by definition - this is a maximum value integer can be! So your condition factorial(n) > int_max_size is always going to be false.
Moreover, there is a logical flaw in your approach. You calculate the value first and than check if it is less than maximum value allowed. By that time it is too late! You have already calculated the value and went through any overflows you might have encountered. Any check you might be performing should be performed while you are still doing your calculations.
In essence, you need to check if multiplying X by Z will be within allowed range without actually doing the multiplication (unfortunately, C++ is very strict in leaving signed integer overflow undefined behavior, so you can't try and see.).
So how do you check if X * Y will be lesser than Z? One approach would be to divide Z by Y before engaging in calculation. If you end up with the number which is lesser than X, you know that multiplying X by Y will result in overflow.
I believe, you know have enough information to code the solution yourself.

if statement not evaluating to false? Program giving strange output. Why?

I have to write a program that receives unsigned inputs and places them in an array of unsigned values. If a non-unsigned value is entered, I call a function called "die" to output an error message, and terminate the program. Here is the code I have written for my input function:
void input(unsigned a[], unsigned elements){
cout << "Enter unsigned numbers one at a time, each followed by enter." << endl;
for (unsigned i = 0; i < elements;i++){
cout << "[" << i << "]: "; // outputs each index as user is inputting
cin >> a[i];
if ( sizeof(a[i]) != sizeof(unsigned) || a[i]<0 ){
die("Invalid input. Program will now exit.");
}
}
}
I've checked and the die function performs its job properly on its own. Here is the output this code yields when a char is entered:
Enter unsigned numbers one at a time, each followed by enter.
[0]: d
[1]: [2]: [3]: [4]: [5]: [6]: [7]: [8]: [9]: Press any key to continue . . .
As you can see, the die function is never successfully called because the if statement preceding it does not evaluate to be false. Furthermore, I'm not sure why my program shows whitespace for the rest of the values in the array. How could I rewrite the if statement to call the die function whenever the input received is not an unsigned?
This is because your if() expression can never be mathematically evaluated as true.
Let's take a look:
if ( sizeof(a[i]) != sizeof(unsigned) || a[i]<0 ){
Let's break this down into two parts. Part 1:
a[i] is an unsigned. Therefore
sizeof(unsigned) != sizeof(unsigned)
will always be false.
Part 2. And because a[i] is unsigned, it can never be negative, therefore
a[i] < 0
will also always be false.
And that's what your die() will never execute.
Why the presented code doesn't work has been answered previously, I will try to react on MV94's comment how to solve this:
Instead of reading directly into the unsigned int variable, read to signed variable of a bigger size than unsigned int and perform the check before assigning into the a[i]. Exact type choice depends on your architecture (you can try intmax_t from <cstdint>). Of course this will only again handle numbers within some range, if user enters number big enough to exceed your signed type, you have similar problem. As someone mentioned before, check that your input conversion succeeded.

Inifinite loop makes variable come out as 0

I have this piece of code in my school book.
#include<iostream>
using namespace std;
int main() {
int x=10,c=1;
while (c < 5) {
x += x*c;
c *= 2;
c++;
c -= 2;
cout << "X=" << x<<'\n';
}
system("pause");
return 0;
}
As you can see it's an infinite loop, when logically traced, it should show 20,40,80 and so on.
However it always shows 0.
when adding system("pause") after each loop cycle it shows the correct values, but when left as shown above (infinitely looping) it shows zero.
Any ideas of the reason?
c is always 1 no matter what. The loop becomes infinite. Eventually, X becomes 0 due to integer overflow.
c = 1
c *= 2; c = 2
c++; c = 3
c -= 2; c = 1 <-- infinite
Here is my answer for your questions:
Why do you get infinitely looping?
awesomeyi did answer you above, because the condition of the while loop is always true, so it is never ended.
Why does X always equal to 0?
Please pay your attention on X varable, its value will be increased after ending one loop x += x*c. Because you are in the infinitely loop, x's value will be increased forever until greater than the limited value of an integer variable. Then, the value will be set as zero. Please see my output when running your code.
Removing the pause doesn't cause it to always show zero. It just prints output so quickly that zeroes are all you see at the bottom. Add the pause back in and click through about 30-40 iterations and see if it helps you understand what is happening.

Error in while loop?

I made a simple example for counting decimal points but it doesn't stop and doesn't give me the right answer here's my code:
double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
{
b*=10;
count++;
}
cout<<count;
the answer is supposed to be:
3
but instead the while loop keeps running Indefinitely .. what's wrong with my code?
You should have checked the INT_MAX first. The number would be different. It depends on whether you are running the code on a 32-bit or 64-bit machine. If it is way smaller than your initial b, you would definitely end up in the infinite loop. For example, the max of short integer type is 32767. In that case, the condition of your loop would be like this: 76327741.125 - some negative number, larger than 0. however, in the loop, you increased the value of b. The next time, when we hit the condition line, it would be something like this: 76327741.125*10 - some negative number
You should probably set b to be b - int(b), to make sure it doesn't keep increasing (and potentially overflowing).
double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
{
b = b - int(b); // Note the change here.
b*=10;
count++;
}
cout<<count;