Java 1022,
分享于 点击 24330 次 点评:17
Java 1022,
package com.lovo;
/**
* 分数运算;
* @author 周博
*/
import java.util.Scanner;
public class Scoremain {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("**** 分数计算器 ****\n");
System.out.println("请输入第一个分数:");
String str0 = sc.nextLine();
char str1 = str0.charAt(0);
int a1 = Integer.parseInt(str1+"");
char str2 = str0.charAt(2);
int a2 = Integer.parseInt(str2+"");
System.out.println("请输入第二个分数:");
String str4 = sc.nextLine();
char str5 = str4.charAt(0);
int b1 = Integer.parseInt(str5+"");
char str6 = str4.charAt(2);
int b2 = Integer.parseInt(str6+"");
Score s1 = new Score(a1,a2);
Score s2 = new Score(b1,b2);
System.out.printf("请选择:\n");
System.out.print("1.分数加法\n");
System.out.print("2.分数减法\n");
System.out.print("3.分数乘法\n");
System.out.print("4.分数除法\n");
System.out.print("5.分数化简\n");
if(sc.hasNextInt()){
int number = sc.nextInt();
switch(number){
case 1:
System.out.println("加法:"+ s1.add(s2));
break;
case 2:
System.out.println("减法:"+ s1.sub(s2));
break;
case 3:
System.out.println("乘法:"+ s1.mul(s2));
break;
case 4:
System.out.println("除法:"+ s1.div(s2));
break;
case 5:
System.out.println("化简:"+ s1.sim(b1, b2));
break;
default:
System.out.print("选项错误!");
}
}else{
System.out.print("对不起,没有该选项!");
}
sc.close();
}
}
package com.lovo;
public class Score {
private int Molecular;
private int Denominator;
/**
* 构造器;
* @param Molecular
* @param Denominator
*/
public Score(int Molecular, int Denominator) {
this.Molecular = Molecular;
this.Denominator = Denominator;
}
/**
* 加法;
* @param other
* @return
*/
public String add(Score other){
int denPoi =this.Denominator*other.Denominator; //分母*分母的积;
int molSum = this.Molecular*other.Denominator+other.Molecular*this.Denominator; //分子+分子的和;
return sim(molSum,denPoi); //还回化简后的分子和 and 分母积;
}
/**
* 减法;
* @param other
* @return
*/
public String sub(Score other){
int denPoi =this.Denominator*other.Denominator;
int molPoor = this.Molecular*other.Denominator-other.Molecular*other.Denominator;
return sim(molPoor,denPoi);
}
/**
* 乘法;
* @param other
* @return
*/
public String mul(Score other){
int molPio =this.Molecular*other.Molecular;
int denPoi =this.Denominator*other.Denominator;
return sim(molPio,denPoi);
}
/**
* 除法;
* @param other
* @return
*/
public String div(Score other){
int molPio =this.Molecular*other.Denominator;
int denPoi =this.Denominator*other.Molecular;
return sim(molPio,denPoi);
}
/**
* 化简;
* 最大公约数;
* @param a
* @param b
* @return
*/
public String sim(int a,int b){
for(int i=Math.abs(a);i>=1;i--){
if(a%i==0 && b%i==0){
return a/i+"/"+b/i;
}
}
return a+"/"+b;
}
}
相关文章
- 暂无相关文章
用户点评