标签:运算符 分数 href 判断 min 输出 注意 注释 不重复
Random ran = new Random();
随机数方法创建对象int B = ran.nextInt(2);
生成0—1之内的随机数能多次生成题目
uml图:
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(); //两随机数a1、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));
}
}
public Fraction (int numer, int denom)
方法,以及Math.abs(numerator)
来保证算法不出现漏洞。她很美
是天边的火烧云
是日月星辰
但是
我更美
在本周学习中,在小伙伴的帮助下,我对代码有了更深的解读,她的认真及更高效的学习方法让我受益,在这周的磨合中我们的默契度也有了更大的提高,思考问题的时候,会有更多相同的思考,结对学习的过程也是我们相互促进的过程。
标签:运算符 分数 href 判断 min 输出 注意 注释 不重复
原文地址:https://www.cnblogs.com/wangyaojia/p/8910340.html