Issue
While writing a C program and compiling it in fedora 32, I always get this message Floating point exception (core dumped)
when I try to scan user's input from the terminal, and I don't know what i did wrong.
I put some printf
functions in between to know where it stops, and what I found that scanf ("%i", &number);
function doesn't read the input or save it correctly.
This is some of the code:
#include <stdio.h>
int main (void)
{
int number, constant, remain, remain1, mod, count, test;
number = 0;
mod = 1;
count = 0;
printf ("Enter a number to write: \n");
scanf ("%i", &number);
printf ("-1");
constant = number;
test = number;
printf ("0");
if (number < 0)
{
number = number * -1;
printf ("-");
}
printf ("1");
while (test != 0)
{
test /= 10;
count++;
printf ("%i", count);
}
printf ("2");
for (int i = 1; i < count; i++)
{
mod = mod * 10;
}
printf ("3");
while (number != 0)
{
remain = number % mod;
remain1 = constant - remain * mod;
switch (remain)
{
case 0:
printf ("Zero");
break;
case 1:
printf ("One");
break;
case 2:
printf ("Two");
break;
case 3:
printf ("Three");
break;
case 4:
printf ("Four");
break;
case 5:
printf ("Five");
break;
case 6:
printf ("Six");
break;
case 7:
printf ("Seven");
break;
case 8:
printf ("Eight");
break;
case 9:
printf ("Nine");
break;
}
remain = remain1;
mod /= 10;
}
printf ("\n");
return 0;
}
Solution
EDIT as for my original guess - it is division by zero
if(!mod ) // add this if
{printf("Division by zero");exit(0);} //
remain = number % mod;
Always check the result of the scanf
. Yuo do not have any floating point opertions here, but probably you have division by zero somewhere in the code you did not show.
#include <stdio.h>
int main (void)
{
int number, constant, remain, remain1, mod, count, test;
number = 0;
mod = 1;
count = 0;
printf ("Enter a number to write: \n");
if(scanf ("%i", &number) != 1)
{
printf("scanf error\n");
}
else
{
printf ("-1");
constant = number;
test = number;
printf ("0");
if (number < 0)
{
number = number * -1;
printf ("-");
}
printf ("1");
while (test != 0)
{
test /= 10;
count++;
printf ("%i", count);
}
printf ("2");
for (int i = 1; i < count; i++)
{
mod = mod * 10;
}
}
}
Here you have this function made simple:
char *digits[] = {"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
void printWord(int x)
{
int work = x;
long val = 1;
while(work)
{
val *= 10;
work /= 10;
}
val /= 10;
if(x < 0) printf("Minus");
if(!x) val = 10;
do
{
printf("%s", digits[abs(x / val)]);
x %= val;
val /= 10;
}while(x);
}
int main (void)
{
printWord(0);
return 0;
}
Answered By - 0___________ Answer Checked By - Terry (WPSolving Volunteer)