I wrote this C program which compiles just great, but when I enter an input it never stops running and when I force stop it, it says "floating point exception (core dumped)". It is basically a function implemented in a bigger program but we dont need that in this case. So whats the deal?
This is the block of code. I wrote the main function just to test the isPal function.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int NumOfDigits(long long x) {
int sum = 1;
while (x / 10 != 0) {
sum ++;
x = x / 10;
}
return sum;
}
int isPal(long long x) {
int f, c, front, back, sum;
sum = NumOfDigits(x);
c = pow(10,(sum-2));
front = x / pow(10,(sum - 1));
back = x % 10;
f = 1;
while (x != 0 && f == 1) {
if (front == back) {
x = (x / 10) % c;
c /= 100;
sum -=2;
front = x / pow(10,sum);
back = x / 10;
} else {
f = 0;
}
}
if (f) {
return 1;
} else {
return 0;
}
}
int main() {
int f;
long long x;
scanf("%lld\n", &x);
f = isPal(x);
if (f) {
printf("yes"); }
else { printf("no"); }
}
If you are testing with a single digit input, then
sumis one, andc = pow(10,(sum-2));setscto zero, since 10−1 = .1, which becomes zero when converted tointfor assignment toc. Then(x / 10) % cdivides by zero.With other numbers with an odd number of digits,
cwill start non-zero, butc /= 100will eventually change it to zero, again causing(x / 10) % cto divide by zero.You need to change the code to avoid this division by zero.
Additionally, some low-quality
powimplementations return inaccurate results even when the mathematical result is exactly representable. For example,pow(10, 0)may return a number slightly less than one even though it ought to return one. You can correct for that by usinground(pow(10, i))instead ofpow(10, i)(orlroundor one of the other rounding functions).However, when testing whether an input numeral is palindromic, it is often preferable to merely read the numeral as a string and test the characters directly, without converting them to a number.