Java练习 SDUT-3849_分数四则运算

分数四则运算

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

编写程序,实现两个分数的加减法

Input

输入包含多行数据;

每行数据是一个字符串,格式是"a/boc/d",其中a, b, c, d为数字(每个数字保证为正数并且不存在正号)。o是运算符"+"或者"-","*",""。

数据以EOF结束,输入数据保证合法。

Output

直接输出结果,并且注意结果应符合书写习惯,没有多余的符号、分子、分母,并且化简至最简分数形式。

Sample Input

1/100+3/100
1/4-1/2
1/3-1/3
1/2*2/1
1/2\1/2

Sample Output

1/25
-1/4
0
1
1

讲真这道题信息量蛮大的,学到了好多,比如分割要用“\\”来表示“”,转义字符要加“\”之类的。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        str a;
        while(cin.hasNext())
        {
            a = new str(cin.nextLine());
            a.get();
            a.f();
        }
        cin.close();
    }
}

class str
{
    int a,b,c,d;
    String st;
    String []s;
    str(String s)
    {
        st = s;
    }
    void get()
    {
        s = st.split("\\\\|\\*|\\-|/|\\+");
        a = Integer.parseInt(s[0]);
        b = Integer.parseInt(s[1]);
        c = Integer.parseInt(s[2]);
        d = Integer.parseInt(s[3]);
    }
    int gcd(int x,int y)
    {
        return y==0?x:gcd(y,x%y);
    }
    void f()
    {
        int i,x,y;
        char f = 0;
        x = y = 0;
        for(i=0;i<st.length();i++)
        {
            if(st.charAt(i)=='+'||st.charAt(i)=='-'||st.charAt(i)=='*'||st.charAt(i)=='\\')
            {
                f = st.charAt(i);
                break;
            }
        }
        //System.out.println(f);
        if(f=='+')
        {
            x = a * d + c * b;
            y = b * d;
        }
        else if(f=='-')
        {
            x = a * d - c * b;
            y = b * d;
        }
        else if(f=='*')
        {
            x = a * c;
            y = b * d;
        }
        else if(f=='\\')
        {
            x = a * d;
            y = b * c;
        }
        if(x==0)
        {
            System.out.println(0);
            return;
        }
        else if(x%y==0)
        {
            System.out.println(x/y);
            return;
        }
        int ff = 1;
        if(x<0)
        {
            ff = -ff;
            x = -x;
        }
        if(y<0)
        {
            ff = -ff;
            y = -y;
        }
        int q = gcd(x,y);
        x /= q;
        y /= q;
        System.out.printf("%d/%d\n",x*ff,y);
    }
}

猜你喜欢

转载自www.cnblogs.com/luoxiaoyi/p/9938607.html
今日推荐