Reputation: 21
I don't know C++ well, and I don't understand why but this error occurred: Floating point exception (core dumped)
I don't know how can I fix it.
#include <iostream>
using namespace std;
int main() {
int a = 251;
int b = 0;
while (a > 0) {
a = a / 10;
b++;
}
int c = 2;
int d = 1;
while (c <= b) {
d = d * 10;
c++;
}
cout << d;
int answer = 0;
int f = d;
int g = 1;
float help;
while (b > 0) {
help = (a / (d * g)) *(d / f);
answer = answer + (int)help;
a = a % (d * g);
g = g * (1 / 10);
f = f * (1 / 10);
b--;
}
cout << answer;
return 0;
}
Upvotes: 1
Views: 3384
Reputation: 26
Better use:
g = g/10;
f = f/10;
for integral values. Also check for g and f not equal to zero before dividing.
I hope this helps ;)
Upvotes: 0
Reputation: 8228
Whenever you have "core dumped" you can use GDB to investigate your crash: gdb binary core
. Here is what happens in your code:
Program terminated with signal SIGFPE, Arithmetic exception.
#0 (...)
at (...):LINE_NUM
LINE_NUM help = (a /(d * g)) *(d /f);
During second iteration your f
and g
are already equal to 0. In Linux you can catch SIGFPE
signal and handle the error, or you can check the variables in your code before performing a division.
Upvotes: 0
Reputation: 385194
Counter-intuitively, a "floating-point exception" is an exception kicked out by your CPU and/or Operating System when you attempt to perform integer division by zero.
C++ makes this operation undefined; your computer outright prohibits it.
Check all your variables when you step through your program with your debugger, and remember that 1 / 10
is zero, not 0.1, because it's integer division. (This mistake propagates to the next iteration of your loop, where you attempt to use this zero value as a divisor.)
Dividing a floating-point number by zero is more well-defined and ISTR it will kick out the special value inf.
Upvotes: 1