Yêu cầu xây dựng cấu trúc Phân số (gồm tử và mẫu).
Viết chương trình nhập vào 2 phân số, yêu cầu xuất phân số tổng của 2 phân số đó (sau khi rút gọn ra màn hình)
Nếu input có phân số nào có mẫu bằng 0 thì xuất kết quả ra -1
ví dụ 1:
input
1 2
1 3
output
5/6
ví dụ 2:
input
1 2
1 0
output
-1
Link nộp bài: http://upcoder.hcmup.edu.vn/index.php/problems/submit/343/01e2663585613fe2026ef385bd7034dc/C%E1%BB%99ng_2_ph%C3%A2n_s%E1%BB%91
Code tham khảo:
#include <iostream>
#include <stdio.h>
#include <cmath>
using namespace std;
struct phanso
{
int tu;
int mau;
};
phanso a,b, tong;
void nhapdl()
{
cin >>a.tu >> a.mau;
cin >>b.tu >> b.mau;
}
int ucln(int a, int b)
{
int r;
while (a%b!=0)
{
r=a%b;
a=b;
b=r;
}
return b;
}
int main( )
{
nhapdl();
if (a.mau==0 || b.mau==0)
{
cout << "-1";
return 0;
}
tong.tu = a.tu*b.mau + a.mau*b.tu;
tong.mau = a.mau*b.mau;
int UC = ucln(tong.tu,tong.mau);
cout << tong.tu/UC << "/"<< tong.mau/UC;
}
Code tham khảo cộng 2 phân số, sử dụng toán tử
#include <iostream>
using namespace std;
class phanso
{
private:
int tu, mau;
public:
phanso(){}
phanso operator+(phanso b);
friend istream &operator >> (istream &in, phanso &ps);
friend ostream &operator << (ostream &out, phanso ps);
};
istream &operator >> (istream &in, phanso &ps)
{
in >> ps.tu >> ps.mau;
return in;
}
ostream &operator << (ostream &out, phanso ps)
{
if (ps.mau == 0)
out << "-1";
else
out << ps.tu << "/" << ps.mau;
return out;
}
int ucln(int a, int b)
{
int r;
while (b>0)
{
r = a%b;
a = b;
b = r;
}
return a;
}
phanso phanso::operator+(phanso b)
{
phanso c;
c.tu = tu*b.mau + mau*b.tu;
c.mau = mau*b.mau;
int z = ucln(c.tu, c.mau);
c.tu /= z;
c.mau /= z;
return c;
}
int main()
{
phanso a, b;
cin >> a >> b;
cout << a + b;
return 0;
}
keywords: Bài tập căn bản liên quan đến cấu trúc struct