Originally Posted by
TemaRN
could you explain all the commands and functions and whatnot? I'm still new to C, so I have no idea what most of those terms do.
I was just demonstrating the gcd function. To learn how it works, look up "Euclid's algorithm" on Wikipedia.
If you're going to learn the language then you need to be able to look up standard library functions yourself. The standard library functions I used are:
printf
fgets
sscanf
putchar
Look them up and then ask questions if you still don't understand something.
Handling negative values:
Code:
#include <stdio.h>
int gcd(int a, int b) {
while (b != 0) {
int t = b;
b = a % b;
a = t;
}
return a;
}
int main() {
char line[500];
while (1) {
int num, den;
printf("Enter a fraction: ");
fgets(line, sizeof line, stdin);
int pos = 0;
if (sscanf(line, "%d%n", &num, &pos) != 1)
break;
if (sscanf(line+pos, " /%d", &den) != 1)
den = 1;
if (den == 0) {
printf("Error: Division by zero\n");
continue;
}
// Handle negatives (ignoring 2's comp INT_MIN problem)
int neg = 0;
if (num < 0) { num = -num; neg = 1; }
if (den < 0) { den = -den; neg = !neg; }
int g = gcd(num, den);
num /= g;
den /= g;
printf("Lowest terms: %s", neg ? "-" : "");
if (num > den) {
printf("%d ", num / den);
num %= den;
}
if (num != 0)
printf("%d/%d", num, den);
putchar('\n');
}
return 0;
}