Phan so
import java.io.*;
import java.math.*;
import java.util.*;
public class Phanso
{
int ts,ms;
public Phanso()
{
ts=1;
ms=1;
}
public void nhap()
{
Scanner input = new Scanner(System.in);
System.out.println("Nhap tu so: ");
try
{
ts=input.nextInt();
}
catch(Exception e)
{
ts=0;
}
System.out.println("Nhap mau so: ");
try
{
ms=input.nextInt();
}
catch(Exception e)
{
ms=1;
}
}
public Phanso toigian()
{
Phanso a=new Phanso();
int x,y;
x=Math.abs(ts);
y=Math.abs(ms);
while(x!=y)
if(x>y) x=x-y;
else y=y-x;
a.ts=ts/x;
a.ms=ms/y;
return a;
}
public Phanso cong(Phanso y)
{
Phanso z=new Phanso();
z.ts=ts*y.ms+y.ts*ms;
z.ms=ms*y.ms;
return z.toigian();
}
public Phanso tru(Phanso y)
{
Phanso z=new Phanso();
z.ts=ts*y.ms-y.ts*ms;
z.ms=ms*y.ms;
return z.toigian();
}
public void xuat()
{
if (ts==0)
System.out.print("0");
else if(ms==0)
System.out.print("Phan so khong hop le");
else
System.out.print(ts+"/"+ms);
}
public static void main(String[] args)
Phanso a=new Phanso();
Phanso b=new Phanso();
Phanso kq=new Phanso();
System.out.println("Nhap phan so a");
a.nhap();
System.out.println("
Nhap phan so b");
b.nhap();
System.out.print("
Tong hai phan so: ");
kq=a.cong(b);
kq.xuat();
System.out.print("
Hieu hai phan so: ");
kq=a.tru(b);
kq.xuat();
}
}
Bạn đang đọc truyện trên: AzTruyen.Top