統計題目完成數並計算正確率html
設計測試類,利用JUnit測試整數類與分數類的四則運算java
public Fraction (int numer, int denom)
方法,以及Math.abs(numerator)
來保證算法不出現漏洞。除此以外還要注意分子分母計算的一些限定特性。咱們一樣加進代碼裏。git
源代碼及分析註釋:算法
import java.util.Random; public class Fraction { private int numerator, denominator; //定義分母、分子 public Fraction (int numer, int denom) { if(denom == 0 ) //分子爲0 denom = 1; if (denom < 0) //若分母小於0,則取分母爲正值,分子爲負值 { numer = numer * -1; denom = denom * -1; } numerator = numer; denominator = denom; reduce(); } public int getNumerator() { return numerator; } public int getDenominator() { return denominator; } public Fraction add(Fraction op2) //實現真分數加法運算 { int commonDenominator = denominator * op2.getDenominator(); //兩隨機數a一、a2的分母相乘,進行通分 int numerator1 = numerator * op2.getDenominator(); //a1的分子=a1的分子與a2的分母相乘 int numerator2 = op2.getNumerator() * denominator; //a2的分子=a2的分子與a1的分母相乘 int sum = numerator1 + numerator2; //將通分事後的兩個隨機數相加 System.out.print("("+this.toString()+")" + " + " + "("+op2.toString()+")" + "="); return new Fraction (sum, commonDenominator); } public Fraction subtract(Fraction op2) //實現真分數減法運算 { int commonDenominator = denominator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator2 = op2.getNumerator() * denominator; int difference = numerator1 - numerator2; System.out.print("("+this.toString()+")" + " - " + "("+op2.toString()+")" + "="); return new Fraction(difference,commonDenominator); } public Fraction multiply (Fraction op2) //實現真分數乘法運算 { int numer = numerator * op2.getNumerator(); int denom = denominator * op2.getDenominator(); System.out.print("("+this.toString()+")" + " * " + "("+op2.toString()+")" + "="); return new Fraction (numer, denom); } public Fraction divide (Fraction op2) //實現真分數除法運算 { int numer = numerator * op2.getDenominator(); int denom = denominator * op2.getNumerator(); System.out.print("("+this.toString()+")" + " / " + "("+op2.toString()+")" + "="); return new Fraction (numer, denom); } public String toString() //輸出格式及限定 { String result; if (numerator == 0) //分子爲0,結果爲0 result = "0"; else if(denominator == 0) //分母不能爲0 return "錯誤!分母不能爲0"; else if (denominator == 1) //分母爲1,結果取分子值 result = numerator + ""; else result = numerator + "/" + denominator; //按分數形式輸出結果 return result; } private void reduce() { if (numerator != 0) { int common = gcd (Math.abs(numerator), denominator); //取分子分母最大公因子 numerator = numerator / common; //約分 denominator = denominator / common; } } private int gcd (int num1, int num2) //計算最大公因子 { if(num2==0) return num1; else return gcd(num2,num1%num2); } public static Fraction obj(){ //生成隨機數 Random ran = new Random(); return new Fraction(ran.nextInt(100),ran.nextInt(100)); } }
步驟 | 耗時 | 百分比 |
---|---|---|
需求分析 | 20min | 16% |
設計 | 30min | 24% |
代碼實現 | 40min | 32% |
測試 | 20min | 16% |
分析總結 | 15min | 12% |