Floating Exception

I'm new to this forum and how to use the "insert code" tool, so I'd appreciate help on that as well. In the following code, I get the error "Floating exception (core dumped)" and am not sure where it is coming from. Any help would be appreciated. The function is supposed to scan a fraction, then print the fraction again along with its reduced form.

#include <stdio.h>
#include <string.h>

typedef struct{
int numer, denom;
} frac_t;

frac_t get_fraction(void);
frac_t reduce_fraction(frac_t fract);
void print_fraction(frac_t fract);

#define nsize 20

int
main(void)
{
frac_t frac;

printf("Input fraction (num/dem): ");
frac = get_fraction();
print_fraction(frac);
printf("=");
print_fraction(reduce_fraction(frac));

return(0);
}

frac_t
get_fraction(void)
{
char fraction[nsize];
int i, status;
frac_t frac;

gets(fraction);
status = 0;

for(i = 0; i < strlen(fraction); i++){
frac.numer = 0;
frac.denom = 0;
if(status == 1)
frac.denom = (10 * frac.denom) + (int) fraction[i];
if((int)fraction[i] == (int) "/")
status = 1;
if(status == 0)
frac.numer = (10 * frac.numer) + (int) fraction[i];
}

return(frac);
}

void
print_fraction(frac_t frac)
{
printf("%d/%d", frac.numer, frac.denom);
}

frac_t
reduce_fraction(frac_t frac)
{
int top, gcd, track;

if(frac.numer < frac.denom)
top = frac.numer;
else top = frac.denom;

for(track = 1; track <= top; track++){
if((frac.numer % track) == 0 && (frac.denom % track) == 0)
gcd = track;
}

frac.numer = frac.numer / gcd;
frac.denom = frac.denom / gcd;

return(frac);
}


To use code format, copy your code to the text box, then use either of these methods:
* Put [code] before and [/code] after it.
* Select it, then click the "insert code" button to the right of the text box. It will do what I explained above automatically.
I'm glad someone actually asked how to do it instead of just copying the code anyway.

It looks to me like you reinvented the wheel a bit with that get_fraction() function. There's already a method for converting a C string to an integer: int atoi(char*)
strpbrk() would help you parse the fraction, but I think it'd be simpler if you just entered the numbers separately.

Line 45: (int) "/"
This is invalid. You must have meant this: '/'

Test output:
Input fraction (num/dem): 12/3
0/51=0/0

No exception, but something tells me that 0/0 isn't quite right.
You mean you got it to work after replacing the '/' and atoi? Mine is still giving me the floating exception error.
(int)fraction[i] does not convert the ASCII character '1' to the integer 1, it converts it to the integer 49 (0x31).

Also get_fraction() zeroes out the numerator and denominator every time through the loop which is not what you want.

No, the test was run ran using the original minus the (int)"/".
Last edited on
Topic archived. No new replies allowed.