Java練習 SDUT-3849_分數四則運算
阿新 • • 發佈:2018-11-10
分數四則運算
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); } }