1034(20)

思路:求最简分式需要求最大公约数,所以需要新建两个函数,首先是求最大公约数的函数,其次是求最简分式的函数,这里面用到最大公约数;再然后是算术运算的四个方法,这里面用到求最简分式的方法。在看网上答案之前,其实也已经有了思路,但是写不出来。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
    // write your code here
        Scanner sc=new Scanner(System.in);
        String[] input=sc.nextLine().split("[\\s/]");
        sc.close();
        long a1=Integer.parseInt(input[0]);
        long b1=Integer.parseInt(input[1]);
        long a2=Integer.parseInt(input[2]);
        long b2=Integer.parseInt(input[3]);

        if (b1!=0&&b2!=0){
            add(a1, b1, a2, b2);
            minus(a1, b1, a2, b2);
            mutilply(a1, b1, a2, b2);
            divide(a1, b1, a2, b2);
        }
    }
    public static void tackle(long a,long b){
        if (a==0){
            System.out.print(0);
            return;
        }
        boolean isMinus=a>0?false:true;
        if (isMinus){//a若为负数,输出符号,且将a取反
            System.out.print("(-");
            a=-a;
        }
        long gcd=getGcd(a,b);//获取ab的最大公约数
        a=a/gcd;
        b=b/gcd;
        if (a%b==0){
            System.out.print(a/b);
        }else if (Math.abs(a)>b){
            System.out.print(a/b+" "+(a%b)%b+"/"+b);//最简分式
        }else if (a==b){
            System.out.print(1);
        }else {
            System.out.print(a+"/"+b);
        }

        if (isMinus){
            System.out.print(")");
        }


    }
    public static void divide(long a1,long b1,long a2,long b2){
        tackle(a1,b1);
        System.out.print(" / ");
        tackle(a2,b2);
        System.out.print(" = ");
        if (a2==0){
            System.out.print("Inf");
        }else if (a2<0){
            tackle(-1*a1*b2,-1*a2*b1);
        }else{
            tackle(a1*b2,a2*b1);
        }

    }

    public static void mutilply(long a1,long b1,long a2,long b2){
        tackle(a1,b1);
        System.out.print(" * ");
        tackle(a2,b2);
        System.out.print(" = ");
        tackle(a1*a2,b1*b2);
        System.out.println();
    }

    public static void minus(long a1,long b1,long a2,long b2){
        tackle(a1,b1);
        System.out.print(" - ");
        tackle(a2,b2);
        System.out.print(" = ");
        tackle(a1*b2-a2*b1,b1*b2);
        System.out.println();

    }
    public static void add(long a1,long b1,long a2,long b2){
        tackle(a1,b1);
        System.out.print(" + ");
        tackle(a2,b2);
        System.out.print(" = ");
        tackle(a1*b2+a2*b1,b1*b2);
        System.out.println();


    }
    /*写一个获取最简分式的函数,求商之后就是求简化后的分式,
    思路:将分子分母同时除以最大公约数,所以需要写一个求最大公约数的函数*/
    public static long getGcd(long a,long b){
        long temp;
        while(a%b!=0){
            temp=a%b;
            a=b;
            b=temp;
        }
        return b;
    }
}

猜你喜欢

转载自www.cnblogs.com/zhuzehua/p/9811348.html
今日推荐