I am creating a program that verifies that an integer is a valid number for a chosen base. The program conditionally throws a Floating point exception even though I am fairly certain that it is impossible for a division by 0, and I have double checked to make sure my variables are initialized.
const int MAX_DIGIT = 5;
int num, base;
int digit = 1;
bool verified_num = true;
cin>>num;
cin>>base;
while (verified_num && digit < pow(10, MAX_DIGIT)) {
if (num % (digit * 10) / digit >= base)
verified_num = false;
digit *= 10;
}
if (verified_num)
cout<<"\n"<<num<<" is a valid base "<<base<<" number!\n";
else
cout<<"\n"<<num<<" is not a valid base "<<base<<" number!\n";
This code works properly when the number is invalid. For example, when num = 54321 and base = 3 the output is
"54321 is not a valid base 3 number!"
Any time the number is valid, however, an error occurs. For example, when num = 12345 and base = 6
Floating point exception (core dumped)
I cannot figure out why this is happening, since in the first example,
if (num % (digit * 10) / digit >= base)
evaluates to false several times and does not cause an error
I am running this code on GCC 7.3.0, and the code seems to work on a couple online compilers that I have tried
EDIT: It appears I made an error in copying my code that concealed the error. In the original code, the variable digit was accidentally stored in a short integer and was overflowing unless the loop exited early. Thank you to everyone that gave their insight