Cách sử dụng Kiểu dữ liệu cấu trúc: Struct phân số

0
49060

Bài toán:

Khai báo cấu trúc PhanSo cần thiết lưu trữ thông tin phân số, sau đó thực hiện các chức năng:

  • Viết hàm nhập vào phân số.
  • Viết hàm xuất phân số.
  • Kiểm tra phân số mẫu phải khác 0.
  • Viết hàm tối giản phân số.
  • Nhập vào 2 phân số. Tính tổng, hiệu, tích và thương của hai phân số.

Xử lý bài toán:

Khai báo thư viện

#include<stdio.h>
#include<conio.h>
#include<math.h>

Khai báo struct phân số

struct phanso
{
	int tu;
	int mau;
};

Khai báo các hàm cần sử dụng

void nhapphanso(phanso &ps);
void xuatphanso(phanso ps);
int ULCN(int a, int b);
void rutgon(phanso &ps);
phanso tongps(phanso x,phanso y);
phanso hieups(phanso a,phanso b);
phanso tichps(phanso a,phanso b);
phanso thuongps(phanso a,phanso b);

Viết hàm nhập

void nhapphanso(phanso &ps)
{
	printf("\nNhap vao tu so ");
	scanf("%d",&ps.tu);
	do
	{
		printf("\nNhap vao mau so ");
		scanf("%d",&ps.mau);
		if(ps.mau==0)
			printf("\nMau phai khac khong\nVui long kiem tra lai");
	}while(ps.mau==0);
}

Viết hàm xuất

void xuatphanso(phanso ps)
{
	printf("Phan so: %d / %d",ps.tu,ps.mau);
}

Viết hàm tìm ước chung lớn nhất

int UCLN(int a, int b)
{
	a=abs(a);
	b=abs(b);
	while(a!=b)
	{
		if(a>b)
			a=a-b;
		else
			b=b-a;
	}
	return a;
}

Viết hàm tối giản phân số

void rutgon(phanso &ps)
{
	int c=UCLN(ps.tu,ps.mau);
	ps.tu=ps.tu/c;
	ps.mau=ps.mau/c;
}

Viết hàm tính tổng

phanso tongps(phanso a,phanso b)
{
	phanso tong;
	tong.tu=a.tu*b.mau+b.tu*a.mau;
    tong.mau=a.mau*b.mau;
	rutgon(tong);
	return tong;
}

Viết hàm tính hiệu

phanso hieups(phanso a,phanso b)
{
	phanso h;
	h.tu=a.tu*b.mau-b.tu*a.mau;
    h.mau=a.mau*b.mau;
	rutgon(h);
	return h;
}

Viết hàm tính tích

phanso tichps(phanso a,phanso b)
{
	phanso tich;
	tich.tu=a.tu*b.tu;
	tich.mau=a.mau*b.mau;
	rutgon(tich);
	return tich;
}

Viết hàm tính thương

phanso thuongps(phanso a,phanso b)
{
	phanso thuong;
	thuong.tu=a.tu*b.mau;
	thuong.mau=a.mau*b.tu;
	rutgon(thuong);
	return thuong;
}

Hàm main

void main()
{
	phanso x,y;
	printf("\nNhap phan so thu nhat ");
	nhapphanso(x);
	xuatphanso(x);
	printf("\nNhap phan so thu 2");
	nhapphanso(y);
	xuatphanso(y);
	phanso tong= tongps(x,y);
	printf("\n tong ");
	xuatphanso(tong);
	phanso hieu=hieups(x,y);
	printf("\nHieu ");
	xuatphanso(hieu);
	phanso tich=tichps(x,y);
	printf("\nTich ");
	xuatphanso(tich);
	phanso thuong=thuongps(x,y);
	printf("\nThuong ");
	xuatphanso(thuong);
	getch();
	
}

Xem thêm: Mảng Struct và ví dụ ứng dụng

Chúc các bạn thành công!

This site uses Akismet to reduce spam. Learn how your comment data is processed.