概述
分数加减乘除案例
本案例是为了帮助我们更加深刻到了解面向对象,直接上代码:
分数类
package com.mfs.test;
public class FractionalNumber {
public int numerator; // 分子
public int denominator; // 分母
public FractionalNumber(int numerator, int denominator) {
if (numerator == 0) {
this.numerator = numerator;
this.denominator = denominator;
}
else {
int com = maxCom(Math.abs(numerator), Math.abs(denominator));//求最大公约数
if (denominator < 0) {
numerator = -numerator;
denominator = -denominator;
}
this.numerator = numerator / com;
this.denominator = denominator / com;
}
}
private int maxCom(int a, int b) { // 求最大公约数
if (a < b) {
int c = a;
a = b;
b = c;
}
int r = 0;
try {
r = a % b;
} catch (Exception e) {
System.out.println(e.getMessage());
} // 分母为零时异常处理
while (r != 0) {
a = b;
b = r;
r = a % b;
}
return b;
}
public FractionalNumber add(int numerator, int denominator) {// 加
int d = denominator;
denominator = this.denominator * denominator;
numerator = this.numerator * d + numerator * this.denominator;
return new FractionalNumber(numerator, denominator);
}
public FractionalNumber sub(int numerator, int denominator) {// 减
int d = denominator;
denominator = this.denominator * denominator;
numerator = this.numerator * d - numerator * this.denominator;
return new FractionalNumber(numerator, denominator);
}
public FractionalNumber mul(int numerator, int denominator) {// 乘
denominator = this.denominator * denominator;
numerator = this.numerator * numerator;
return new FractionalNumber(numerator, denominator);
}
public FractionalNumber div(int numerator, int denominator) {// 除
int d = denominator;
denominator = this.denominator * numerator;
numerator = this.numerator * d;
return new FractionalNumber(numerator, denominator);
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
}
main方法,测试类
package com.mfs.test;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String str = sc.next();//读取输入的算式
int a = Integer.parseInt(str.charAt(0)+"");//获得两个分数的分子分母,考虑到项目的复杂性,
int b = Integer.parseInt(str.charAt(2)+"");//输入的算式各项只能是正的,并且分子分母只能一位
int c = Integer.parseInt(str.charAt(4)+"");
int d = Integer.parseInt(str.charAt(6)+"");
FractionalNumber f1 = new FractionalNumber(a, b);
switch(str.charAt(3)) {
case '+': System.out.println(f1.add(c, d).toString());
break;
case '-':System.out.println(f1.sub(c, d).toString());
break;
case '*':System.out.println(f1.mul(c, d).toString());
break;
case '/':System.out.println(f1.div(c, d).toString());
break;
}
}
}
最后
以上就是苗条星月为你收集整理的Java学习--面向对象2:有理数加减乘除的实现的全部内容,希望文章能够帮你解决Java学习--面向对象2:有理数加减乘除的实现所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复