分数四则运算_JAVA
生活随笔
收集整理的這篇文章主要介紹了
分数四则运算_JAVA
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Description
編寫程序,實現(xiàn)兩個分數(shù)的加減法
Input
輸入包含多行數(shù)據(jù);
每行數(shù)據(jù)是一個字符串,格式是"a/boc/d",其中a, b, c, d為數(shù)字(每個數(shù)字保證為正數(shù)并且不存在正號)。o是運算符"+“或者”-","*",""。
數(shù)據(jù)以EOF結(jié)束,輸入數(shù)據(jù)保證合法。
Output
直接輸出結(jié)果,并且注意結(jié)果應(yīng)符合書寫習(xí)慣,沒有多余的符號、分子、分母,并且化簡至最簡分數(shù)形式。
Sample
Input
1/100+3/100
1/4-1/2
1/3-1/3
1/2*2/1
1/2\1/2
Output
1/25
-1/4
0
1
import java.util.Scanner;class F{int a;int b;public F(int a, int b) {this.a = a;this.b = b;}public int maxnum(int a, int b) {if (a % b == 0)return b;else {int x = maxnum(b, a % b);return x;}} }class math{int a;int b;public math(int a, int b) {this.a = a;this.b = b;}public void cal(math m, char r) {int x;int y;if(r == '+') {x = this.a * m.b + this.b * m.a;y = this.b * m.b;}else if(r == '-') {x = this.a * m.b - this.b * m.a;y = this.b*m.b;}else if(r == '*') {x = this.a * m.a;y = this.b * m.b;}else {int tt = m.a;m.a = m.b;m.b = tt;x = this.a * m.a;y = this.b * m.b;}if(x == 0)System.out.println("0");else {F ff = new F(x,y);int t = ff.maxnum(x, y);x /= t;y /= t;if(y == -1) {System.out.println(-x);}else if(y == 1) {System.out.println(x);}else if(y < 0) {y = -y;x = -x;System.out.println(x + "/" + y);}elseSystem.out.println(x + "/" + y);}}}public class Main {public static void main(String[] args) {Scanner reader = new Scanner(System.in);while(reader.hasNext()) {String str = reader.next();String[] s=str.split("\\+|-|\\*|/|\\\\");char r = '+';for(int i = 0; i < str.length(); i++) {if(str.charAt(i) == '+' || str.charAt(i) == '-' || str.charAt(i) == '*' || str.charAt(i) == '\\') {r = str.charAt(i);break;}}int a = Integer.parseInt(s[0]);int b = Integer.parseInt(s[1]);int c = Integer.parseInt(s[2]);int d = Integer.parseInt(s[3]);math x = new math(a, b);math y = new math(c, d);x.cal(y, r);}reader.close();} } 《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的分数四则运算_JAVA的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 谁是最强的女汉子_JAVA
- 下一篇: 手机键盘_JAVA