Last active
December 3, 2021 02:13
-
-
Save duyet/9087977 to your computer and use it in GitHub Desktop.
Xây dựng 1 chương trình nhập 1 mảng phân số Tính TBC các phân số trong mảng , tìm phân số bé nhất trong mảng , xắp xếp mảng phân số theo thứ tự giảm dần về tử số ...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct { | |
int tuSo, mauSo; | |
} frac; | |
int UCLN(int a, int b) { | |
while (a != b) { | |
if (a > b) a -= b; | |
else if (b > a) b -= a; | |
} | |
return a; | |
} | |
frac plusFrac(frac a, frac b) { | |
frac ans; | |
ans.mauSo = a.mauSo * b.mauSo; | |
ans.tuSo = a.tuSo * b.mauSo + b.tuSo * a.mauSo; | |
return ans; | |
} | |
frac TBC(frac a[], int n) { | |
frac ans = a[0]; | |
for (int i = 1; i < n; i++) { | |
ans = plusFrac(ans, a[i]); | |
} | |
ans.mauSo *= n; | |
// Rut gon phan so | |
ans.mauSo /= UCLN(ans.tuSo, ans.mauSo); | |
ans.tuSo /= UCLN(ans.tuSo, ans.mauSo); | |
return ans; | |
} | |
int min(frac a[], int n) { | |
int min = 0; float minValue = (float) a[0].tuSo / a[0].mauSo; | |
for (int i = 1; i < n; i++) { | |
if (minValue > ((float) a[i].tuSo / a[i].mauSo)) { | |
minValue = (float) a[i].tuSo / a[i].mauSo; | |
min = i; | |
} | |
} | |
return min; | |
} | |
void swap(frac &a, frac &b) { | |
frac tmp = a; | |
a = b; | |
b = tmp; | |
} | |
void sort(frac a[], int n) { | |
for (int i = 0; i < n - 1; i++) { | |
for (int j = i + 1; j < n; j++) { | |
if (a[i].tuSo < a[j].tuSo) { | |
swap(a[i], a[j]); | |
} | |
} | |
} | |
} | |
void printFrac(frac a[], int n) { | |
for (int i = 0; i < n; i++) { | |
printf("%d/%d ", a[i].tuSo, a[i].mauSo); | |
} | |
} | |
int main() { | |
frac * a, *b; | |
int n; | |
do { | |
printf("Nhap so luong phan tu cua mang: "); | |
scanf_s("%d", &n); | |
} while (n < 0); | |
a = (frac*) malloc(sizeof(frac)); | |
for (int i = 0; i < n; i++) { | |
printf("%d. Phan so (a/b): ", i+1); | |
do {scanf_s("%d/%d", &a[i].tuSo, &a[i].mauSo);} while (a[i].mauSo == 0); | |
} | |
printf("Trung binh cong: %d/%d\n", TBC(a, n).tuSo, TBC(a, n).mauSo); | |
printf("Phan so nho nhat: %d/%d\n", a[min(a, n)].tuSo, a[min(a, n)].mauSo); | |
sort(a, n); | |
printf("Phan so sau khi sap xep: "); printFrac(a, n); printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment