分数加减法_JAVA
生活随笔
收集整理的這篇文章主要介紹了
分数加减法_JAVA
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Description
編寫一個C程序,實現(xiàn)兩個分數(shù)的加減法
Input
輸入包含多行數(shù)據(jù)
每行數(shù)據(jù)是一個字符串,格式是"a/boc/d"。
其中a, b, c, d是一個0-9的整數(shù)。o是運算符"+“或者”-"。
數(shù)據(jù)以EOF結束
輸入數(shù)據(jù)保證合法
Output
對于輸入數(shù)據(jù)的每一行輸出兩個分數(shù)的運算結果。
注意結果應符合書寫習慣,沒有多余的符號、分子、分母,并且化簡至最簡分數(shù)
Sample
Input
1/8+3/8
1/4-1/2
1/3-1/3
Output
1/2
-1/4
0
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) {int x = this.a * m.b + this.b * m.a;int 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 s = reader.next();int a = s.charAt(0) - '0';int b = s.charAt(2) - '0';int c = s.charAt(4) - '0';int d = s.charAt(6) - '0';if(s.charAt(3) == '-')c = -c;math x = new math(a, b);math y = new math(c, d);x.cal(y);}reader.close();} }總結
以上是生活随笔為你收集整理的分数加减法_JAVA的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 织女的红线_JAVA
- 下一篇: 答答租车系统(面向对象综合练习)_JAV