设计题目——分数的加减乘除
1. 基本要求
1.成员变量 x 和 y,分别存放分子和分母, 要求分数以最简形式存放。例如:分数 2/4 应简化为 1/2。
2.定义成员函数 add、sub、multiply 和 div,求两个分数的和差积商。计算结果仍以最简形式存放。
2. 运行效果图
3. 设计方案
- 从输入设备中输入两个分数。保存在Sring中
- 使用String方法 split 以“/”为分隔符 分割。结果保存在 String[]中
- 定义a1 a2 b1 b2 分别保存 分数的 分子和分母
- 声明构造方法Fraction (int f1 ,int f2)
- 定义 成员方法 分别计算 分数的加减乘除。返回 Fraction 对象
- 定义asFraction(Fraction other); 将返回的Fraction对象的分子和分母进行约分。
4. 功能模块划分
a. 在main 中,获得两个分数并且分割分子分母 声明Fraction对象
b. 调用 加减乘除 方法进行计算
c. 调用静态方法asFraction 进行约分 输出。+
5.算法思想
最重要的一点就是,在进行分式运算以后,返回Fraction对象,方便约分的进行
6. 代码实现
package fraction;
import java.util.Scanner;
import java.lang.Math;
public class Fraction {
public static void main(String[] args) {
int a1,a2,b1,b2;
Scanner sc = new Scanner(System.in);
System.out.print("a = ");//输入第一个分数
String str1 = sc.next();
System.out.print("b = ");//输入第二个分数
String str2 = sc.next();
String[] split1 = str1.split("/");//使用 字符串的分割方法 将"/" 作为分割标志
String[] split2 = str2.split("/");//保存到字符串数组中
a1 = Integer.parseInt(split1[0]);// 将分割好的字符串数组 转换成整型的分子分母
a2 = Integer.parseInt(split1[1]);
b1 = Integer.parseInt(split2[0]);
b2 = Integer.parseInt(split2[1]);
Fraction f1 = new Fraction(a1,a2);//实例化 对象 a1 a2 分别做分子和分母
Fraction f2 = new Fraction(b1,b2);
System.out.println("a + b =" + asFraction(f1.add(f2)));
System.out.println("a - b =" + asFraction(f1.sub(f2)));
System.out.println("a * b =" + asFraction(f1.multiply(f2)));
System.out.println("a / b =" + asFraction(f1.div(f2)));
sc.close();
}
//约分
public static String asFraction(Fraction other) {
int i,j;
i=other.f1;j=other.f2;
if(i==0) {
return "0";
}
if(i>0&&j>0) {//没有负号的输出 由return 决定
int r ;
while(i>0) {
r = j%i;
j=i;
i=r;
}
i=other.f1/j;//原先的参数值 除以 最大公约数 的到约分后的值
j=other.f2/j;//原先的参数值 除以 最大公约数 的到约分后的值
i=Math.abs(i);
j=Math.abs(j);
return (i + "/" + j);
}else { //有负号的输出
i=Math.abs(i); //先将 i,j 绝对值。计算i 和 j 的最大公约数
j=Math.abs(j);
int r ;
while(i>0) {
r=j%i;
j=i;
i=r;
}
i=Math.abs(other.f1)/j;//原先的参数值 除以 最大公约数 的到约分后的值
j=Math.abs(other.f2)/j;//原先的参数值 除以 最大公约数 的到约分后的值
return("-" + i + "/" + j);
}
}
private int f1; //分子
private int f2; //分母
//构造 Fraction 函数
public Fraction(int f1,int f2) {
if(f2 == 0){throw new IllegalArgumentException("分母不能为0");}
this.f1=f1;
this.f2=f2;
}
/** 加法 */
public Fraction add(Fraction other) {
int fm = this.f2 * other.f2;//分母相乘
int fz = this.f1 * other.f2 + other.f1 * this.f2; // 分子先乘对方分母再相加
return new Fraction(fz, fm);
}
/** 减法 */
public Fraction sub(Fraction other){
int fm = this.f2 * other.f2; // 分母相乘
int fz = this.f1 * other.f2 - other.f1 * this.f2; // 分子先乘对方分母在相减
return new Fraction(fz, fm);
}
/**乘法 */
public Fraction multiply(Fraction other){
int fm = this.f2 * other.f2; //分母相乘
int fz = this.f1 * other.f1; //分子相乘
return new Fraction(fz, fm);
}
/** 除法 */
public Fraction div(Fraction other){
int fm = this.f2 * other.f1; //分子乘分母
int fz = this.f1 * other.f2;//分子乘分母
return new Fraction(fz, fm);
}
}