mirror of
https://gitlab.gwdg.de/j.hahn02/university.git
synced 2025-12-31 22:34:25 -05:00
86 lines
1.6 KiB
C
86 lines
1.6 KiB
C
#include<stdlib.h>
|
|
#include<stdio.h>
|
|
#include<time.h>
|
|
|
|
// This is the definition for a fraction from the task
|
|
typedef struct {
|
|
int n;
|
|
int d;
|
|
} fraction_t;
|
|
|
|
fraction_t sub_frac(fraction_t *a, fraction_t *b) {
|
|
// this function should substract fractions from anonther
|
|
// with the condition that a/b - c/d = (ad + bc)/(bd)
|
|
// also check that the negative sign always is on the nominator
|
|
|
|
fraction_t r = {0};
|
|
|
|
// Check for edge cases
|
|
if (!a || !b || a->d == 0 || b->d == 0) return r;
|
|
|
|
|
|
// Calculate the result
|
|
r.n = a->n * b->d - a->d * b->n;
|
|
r.d = a->d * b->d;
|
|
|
|
// flip the signs
|
|
if (r.d < 0) {
|
|
r.d *= -1; r.n *= -1;
|
|
}
|
|
|
|
return r;
|
|
}
|
|
|
|
fraction_t *max_frac(fraction_t a[], int l) {
|
|
// This function should return a pointer to the biggest fraction in the array
|
|
// Do this with the condition that if a - b < 0 it follows that a < b.
|
|
|
|
// Init the max
|
|
fraction_t *m = a;
|
|
|
|
// Find the max
|
|
for (int i = 1; i < l; i++) {
|
|
if (sub_frac(m, a + i).n < 0) {
|
|
m = a + i;
|
|
}
|
|
}
|
|
|
|
return m;
|
|
}
|
|
|
|
#define N 10
|
|
|
|
void print_frac(fraction_t *f) {
|
|
printf("%d/%d ", f->n, f->d);
|
|
}
|
|
|
|
int main() {
|
|
// Seed the randomness
|
|
srand(time(NULL));
|
|
|
|
// Generate a list of random fractions
|
|
fraction_t l[N];
|
|
for (int i = 0; i < N; i++) {
|
|
fraction_t r = {rand()%5+1, rand()%5+1};
|
|
|
|
// Also give a random sign
|
|
if (rand()%2 == 0) {
|
|
r.n *= -1;
|
|
}
|
|
l[i] = r;
|
|
}
|
|
|
|
// print the fracions
|
|
for (int i = 0; i < N; i++) {
|
|
print_frac(l +i);
|
|
}
|
|
putchar('\n');
|
|
|
|
// Print the max Fraction
|
|
fraction_t *max = max_frac(l, N);
|
|
printf("The max fraction is: ");
|
|
print_frac(max);
|
|
putchar('\n');
|
|
}
|
|
|