basic-c/sources/fractions.c

59 lines
1.4 KiB
C
Raw Permalink Normal View History

2021-09-30 16:01:28 +03:00
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int nat; // natural (integer)
int num; // numerator
int den; // denominator
} Fraction;
void frPrint(Fraction f) {
if (f.num != 0)
if (f.nat == 0)
printf("%d / %d", f.num, f.den);
else
printf("%d %d/%d",f.nat,f.num,f.den);
else
printf("%d", f.nat);
}
void frDesinteger(Fraction *f) {
if (f->nat == 0) return;
int sign = (f->nat < 0) ? -1 : 1;
if (f->nat < 0)
f->num = -f->num;
f->num = f->num + (f->nat * f->den);
f->nat = 0;
}
void frMultiply(Fraction f1, Fraction f2, Fraction *result) {
frDesinteger(&f1);
frDesinteger(&f2);
result->num = f1.num * f2.num;
result->den = f1.den * f2.den;
}
int main(int argc, const char* argv[]){
Fraction f1, f2, result;
// f1 = -1 | 1 /5
f1.nat = -1;
f1.num = 1;
f1.den = 5;
// f2 = 1 | 1 /5
f2.nat = 1;
f2.num = 1;
f2.den = 5;
// result = 0
result.nat = 0;
result.num = 0;
result.den = 0;
printf("Before:\n");
printf(" f1: "); frPrint(f1); printf("\n");
printf(" f2: "); frPrint(f2); printf("\n");
printf("result: "); frPrint(result); printf("\n");
puts("After:");
frMultiply(f1, f2, &result);
printf("result: "); frPrint(result); printf("\n");
}