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

该程序使用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;
    }
}

结果演示

结果不需约分

结果需要约分

结果为整数

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值