有理数的设计

有理数类的设计

1.代码

package Main;
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Rational a = new Rational(sc.nextInt(),sc.nextInt());
		Rational b = new Rational(sc.nextInt(),sc.nextInt());
		sc.close();
	    a.operate1(b).output();	
	    System.out.println();
		a.operate2(b).output();	
		
   }
}
	
	class Rational {										
		int fz, fm;									// 分子,分母

		public int Gcd(int m,int n) {
			int temp;
			while(m%n!=0) {
				temp=n;
				n=m%n;
				m=temp;
			}
			return n;
		}
		public Rational(int fz, int fm) {// 求最大公约数
			this.fz = fz;
			this.fm = fm;
			if (0 != fz && 0 != fm) {					
				long gcd = Gcd(Math.abs(fz), fm);		
				this.fz /= gcd;
				this.fm /= gcd;
			}
		}

		public Rational operate1(Rational num) {	
										// 加法
			return new Rational(fz * num.fm + num.fz * fm, fm * num.fm);
				
												
		}
		public Rational operate2(Rational num) {	
	// 乘法
			return new Rational(fz * num.fz, fm * num.fm);
					
        }

		public void output() {							// 输出
			if (0 == fm) {								// 分母为0
				System.out.print("Inf");
			} else if (0 == fz) {						// 分子为0
				System.out.print(0);
			}
			if (0 == fz % fm) {	
				System.out.print(fz / fm);
		    }else {	
			System.out.print(fz + "/" + fm);
		    }
	}
}

2.代码测试

  1. 尝试描述怎么与c语言的有理数代码相比较,为什么你设计的类更加面向对象?

    C语言是面向过程,将问题分为多个步骤一一实现,使用面向对象的类只需进行导入,可以把问题更方便化。

  2. 别人如何复用你的代码?

    可以把这个类加到他的对应的包里

  3. 别人的代码是否依赖你的属性

    依赖我设置的分子分母的属性,如果变动则无法使用

6.有理数类的public是否设置合适?
合适,使用public可以进行直接的调用,private则可以防止别人修改数据
TEST

posted @ 2020-10-04 12:00  20190211飞飞  阅读(43)  评论(0编辑  收藏  举报