2009年4月13日 星期一

lab Fraction Addition

Write a program to implement a method that can do additions of 2 fractions. You will implement a class called Fraction consisting of a numerator and a denominator. The additions of
2 fractions should be equal to a fraction.
Use 1/2+1/3 as the test.

Hints:
Fraction f1, f2;
f1.add(f2);




class程式碼
------------------------------------------------<程式碼開始>--------------------------------------
public class Fractions {
public int numerator, denominator;
Fractions(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public void add(Fractions f) {
int numerators, denominators;
numerators = f.denominator * this.numerator + f.numerator * this.denominator;
denominators = f.denominator * this.denominator;
System.out.println(numerators + "/" + denominators);
}
}

------------------------------------------------<程式碼結束>--------------------------------------
主程式碼
------------------------------------------------<程式碼開始>--------------------------------------
import java.util.*;
public class FractionAddition {
    public static void main (String args[]) {
Fractions f1, f2;
        f1 = new Fractions(1, 2);
f2 = new Fractions(1, 3);
f1.add(f2);
    }
}
------------------------------------------------<程式碼結束>--------------------------------------
附註:本次lab的寫法只能滿足本題目的用法,對於需要持續相加時會有問題,解決用法請參考下個lab。

沒有留言:

張貼留言