⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 testfraction.java

📁 实现一个复数类
💻 JAVA
字号:
class MyException extends Exception
{
	public String toString()
	{
		return "分母是0!错误!";
	}
};

class Fraction{
	private int f1, f2;

	Fraction(){
		f1 = f2 = 1;
	}
	Fraction(int a, int b){
		f1 = a;
		try{
			isZero(b);
		}
		catch(MyException e){
			System.out.println(e);
		}
		f2 = b;
	}

	int getF1() {return f1;}
	int getF2() {return f2;}
	public String toString(){
		return f1 + "/" + f2;
	}
	public float FloatType(){
		return (float)f1/f2;
	}
	void isZero(int x) throws MyException{
		if(x == 0)
			throw new MyException();
		else
			return ;
	}

	Fraction add(Fraction b){
		int temp1 = f1*b.getF2() + f2*b.getF1();
		int temp2 = f2 * b.getF2();
		Fraction temp = new Fraction(temp1, temp2);
		return temp;
	}
	Fraction sub(Fraction b){
		int temp1 = f1*b.getF2() - f2*b.getF1();
		int temp2 = f2 * b.getF2();
		Fraction temp = new Fraction(temp1, temp2);
		return temp;
	}
	Fraction mul(Fraction b){
		int temp1 = f1 * b.getF1();
		int temp2 = f2 * b.getF2();
		Fraction temp = new Fraction(temp1, temp2);
		return temp;
	}
	Fraction div(Fraction b){
		int temp1 = f1 * b.getF2();
		int temp2 = f2 * b.getF1();
		Fraction temp = new Fraction(temp1, temp2);
		return temp;
	}
};

class testFraction{
	public static void main(String[] args){
		Fraction a = new Fraction(2, 3);
		Fraction b = new Fraction(2, 3);

		Fraction c = a.add(b);
		System.out.println("c = " + c);
		System.out.println("c = " + c.FloatType());

		Fraction d = a.sub(b);
		System.out.println("d = " + d);
		System.out.println("d = " + d.FloatType());

		Fraction e = a.mul(b);
		System.out.println("e = " + e);
		System.out.println("e = " + e.FloatType());

		Fraction f = a.div(b);
		System.out.println("f = " + f);
		System.out.println("f = " + f.FloatType());
	}
};

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -