JAVA作业——两个分数进行减法运算

目录

代码

结果演示

结果不需约分

结果需要约分

结果为整数


代码

package timberman.ui;

import java.util.Scanner;
public class homework {
    public static void main(String[] args) {

        Scanner input =new Scanner(System.in);

        int []first_num=new int [2];
        int []second_num=new int [2];

        System.out.println("请输入第一个数字的分子");
        first_num[0]= input.nextInt();
        System.out.println("请输入第一个数字的分母");
        first_num[1]= input.nextInt();
        System.out.println("请输入第二个数字的分子");
        second_num[0]= input.nextInt();
        System.out.println("请输入第二个数字的分母");
        second_num[1]= input.nextInt();

        long temp_mother=(first_num[1]*second_num[1])/gcd(first_num[1],second_num[1]);
        long temp_son=first_num[0]*(temp_mother/first_num[1])-second_num[0]*(temp_mother/second_num[1]);

        long real_gcd=gcd(temp_son,temp_mother);
        long real_son=temp_son/real_gcd;
        long real_mother=temp_mother/real_gcd;

        if(real_son%real_mother==0){
            System.out.println(real_son/real_mother);
        }
        else{
            System.out.println(real_son+"/"+real_mother);
        }
    }

    public static long gcd(long a,long b) {
        while(b!=0){
            long temp=a%b;
            a=b;
            b=temp;
        }
        return a;
    }
}

结果演示

结果不需约分

结果需要约分

结果为整数

猜你喜欢

转载自blog.csdn.net/timberman666/article/details/130684738