Câu 3.1.a: Cho cấu trúc phân số gồm tử số và mẫu số như sau:
struct PS {int tu, mau;};
- Viết hàm tạo phân số
- Viết hàm in phân số dạng tu/mau
- Viết hàm tính tổng hai phân số, kết quả trả về phân số
Viết chương trình sử dụng các hàm trên nhập hai phân số, tính và in ra màn hình tổng của chúng.
// code Dung NV
#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <math.h>
typedef struct
{
inttu,mau;
}ps;
void taops(int *a,int *b)
{
printf("\nNhap tu so : ");
scanf("%d",&*a);
printf("\nNhap mau so : ");
scanf("%d",&*b);
}
void inps(ps a)
{
printf(" %d/%d ",a.tu,a.mau);
}
int ucln(int x, int y)
{
x = abs(x);
y = abs(y);
while(x!=y)
if (x>y) x=x-y; elsey=y-x;
returnx;
}
ps tongps(ps a,ps b)
{
intuc;
ps c;
c.tu=a.tu*b.mau+b.tu*a.mau;
c.mau=a.mau*b.mau;
uc=ucln(c.tu,c.mau);
c.tu=c.tu/uc;
c.mau=c.mau/uc;
returnc;
}
int _tmain(int argc, _TCHAR* argv[])
{
ps x,y,z;
printf("\nnhap phan so thu nhat : ");
taops(&x.tu,&x.mau);
printf("\nnhap phan so thu hai : ");
taops(&y.tu,&y.mau);
z=tongps(x,y);
printf("\n");
inps(x);
printf("+");
inps(y);
printf("=");
inps(z);
getch();
return0;
}
No comments:
Post a Comment