Câu 3.1.b: 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 mảng n phân số, tính và in ra màn hình tổng của chúng.
// bai1s.cpp : Defines the entry point for the console application.
// code Dung NV
#include"stdafx.h"
#include<stdio.h>
#include<conio.h>
#include<math.h>
typedefstruct
{
inttu,mau;
}ps;
voidtaops(ps a[],int i)
{
printf("\nNhap tu so : ");
scanf("%d",&a[i].tu);
printf("\nNhap mau so : ");
scanf("%d",&a[i].mau);
}
voidinps(ps a)
{
printf(" %d/%d ",a.tu,a.mau);
}
intucln(int x, inty)
{
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;
}
ps tongmangps(int i,ps a[],int n,ps b)
{
b=tongps(b,a[i]);
if(i==n-1) return b;
else
tongmangps(i+1,a,n,b);
}
int_tmain(int argc, _TCHAR* argv[])
{
ps x[300],y,z;
intn,i;
printf("\nnhap so phan tu mang phan so : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nnhap phan so thu %d : ",i);
taops(x,i);
inps(x[i]);
}
y.tu=x[0].tu;
y.mau=x[0].mau;
z=tongmangps(1,x,n,y);
inps(z);
getch();
return0;
}
No comments:
Post a Comment