Java練習 SDUT-2253_分數加減法
阿新 • • 發佈:2018-10-29
pre tput ble 計算 輸入數據 gcd NPU while har
分數加減法
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
編寫一個C程序,實現兩個分數的加減法
Input
輸入包含多行數據
每行數據是一個字符串,格式是"a/boc/d"。
其中a, b, c, d是一個0-9的整數。o是運算符"+"或者"-"。
數據以EOF結束
輸入數據保證合法
Output
對於輸入數據的每一行輸出兩個分數的運算結果。
註意結果應符合書寫習慣,沒有多余的符號、分子、分母,並且化簡至最簡分數
Sample Input
1/8+3/8
1/4-1/2
1/3-1/3
Sample Output
1/2
-1/4
0
題解:同分計算分數的結果然後找分子分母的最大公因子約分化簡。註意分子為0以及分子是分母的倍數的時候。
import java.util.*; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); String s; node a = new node(); while(cin.hasNextLine()) { s = cin.nextLine(); a.ji(s); } cin.close(); } } class node { int a,b,c,d; void get(String s) { a = s.charAt(0) - '0'; b = s.charAt(2) - '0'; c = s.charAt(4) - '0'; d = s.charAt(6) - '0'; } void ji(String s) { int q,w,e; get(s); if(s.charAt(3)=='-') { w = b * d; q = a * d - c * b; } else { w = b * d; q = a * d + c * b; } if(q==0) System.out.println(0); else { e = gcd(w,q); if(w/e==1) System.out.println(q/e); else System.out.printf("%d/%d\n",q/e,w/e); } } int gcd(int a,int b) { if(a<0) a = -a; if(b<0) b = -b; return b==0?a:gcd(b,a%b); } }
Java練習 SDUT-2253_分數加減法