Reduce Proper Fractions
5
A while back ago I wrote this in a simple program I wrote.
Unfortunately, it only reduces proper fractions. If someone wants to rewrite it and make it work with inproper fractions that would be awesome!
Unfortunately, it only reduces proper fractions. If someone wants to rewrite it and make it work with inproper fractions that would be awesome!
struct fraction_t {
int x;
int y;
};
typedef struct fraction_t (FRACTION);
FRACTION reduce_fraction(FRACTION fraction)
{
FRACTION val = fraction;
int i, success = 0;
while (success != 1) {
success = 1;
for (i = 2; i < val.y; i++) {
if ((val.x % i) == 0 && (val.y % i) == 0) {
val.x = val.x / i;
val.y = val.y / i;
success = 0;
break;
}
}
}
return val;
}
int main(int argc, char* argv[])
{
printf("Input Numbers (x / y): ");
scanf("%d / %d", &num1, &num2);
FRACTION inf;
inf.x = num1;
inf.y = num2;
FRACTION outf = reduce_fraction(inf);
printf("%d / %d\n", outf.x, outf.y);
return 0;
}






Then, as far as improper fractions go, try solving them like you would on paper (see below).
By the way, I've never tried to write a fraction-reducing algorithm before, and now I don't think I will. I like yours! It's one for the personal snippet-file . . .
I've got good news, and I've got bad news:
The universe is merely a figment of my imagination.
Now are you ready for the bad news?
// string parser
input = squash_whitespace(input);
strings = split('/',input);
num = strings[0];
denom = strings[1];
// Dealing with improper fractions
(assuming integer arithmetic . . . )
// first find the _actual_ fractional part . . .
int n = num / denom;
num -= (n * denom);
// . . . reduce that . . .
reduce_fraction(&num,&denom)
// . . . and output it as a mixed number or improper fraction
if(want_improper_output) {
num += (n * denom);
improper_fraction_out(num,denom);
}
else {
mixed_number_out(n,num,denom);
}
int num1;
int num2;
Also, throwing in some error checking on the input might be a good idea in case someone decides they want to enter in something other than whole numbers.
Another suggestion would be to ask for the numerator and the demonater seperate of each other, making it a little more intuitive and less likely for the user to make a mistake.
Just my two cents; otherwise this is a nifty little app with potential.