2009年4月27日 星期一

Homework 4-13-2009 Fraction Multiplication

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

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


due date: 4/27/2009


class程式碼
------------------------------------------------<程式碼開始>--------------------------------------
public class Fractions {
private int numerator, denominator;
public Fractions(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public Fractions add(Fractions f) {
int x, a, b;
Fractions ans = new Fractions(1, 1);
ans.numerator = f.denominator * this.numerator + f.numerator * this.denominator;
ans.denominator = f.denominator * this.denominator;
ans.numerator = ans.numerator / reduction (ans.numerator, ans.denominator);
ans.denominator = ans.denominator / reduction (ans.numerator, ans.denominator);
return ans;
}
public Fractions multiply(Fractions f) {
Fractions ans = new Fractions(1, 1);
ans.numerator = f.numerator * this.numerator;
ans.denominator = f.denominator * this.denominator;
ans.numerator = ans.numerator / reduction (ans.numerator, ans.denominator);
ans.denominator = ans.denominator / reduction (ans.numerator, ans.denominator);
return ans;
}
private int reduction(int a, int b) {
int x;
if(a<b) {
x = a;
a = b;
b = x;
}
while (b != 0) {
x = a % b;
a = b;
b = x;
}
return a;
}
public String toString()
{
return (numerator + "/" + denominator);
}
}
------------------------------------------------<程式碼結束>--------------------------------------
主程式碼
------------------------------------------------<程式碼開始>--------------------------------------
import java.util.*;
public class Homework04132009FM {
    public static void main (String args[]) {
Fractions f1, f2, f3, f4;
        f1 = new Fractions(4, 2);
f2 = new Fractions(1, 3);
System.out.println("f1 = " + f1.toString());
System.out.println("f2 = " + f2.toString());
System.out.println("f1 + f2 = " + f1.add(f2).toString());
System.out.println("f1 * f2 = " + f1.multiply(f2).toString() + "\n");
        f3 = new Fractions(5, 6);
f4 = new Fractions(2, 9);
System.out.println("f3 = " + f3.toString());
System.out.println("f4 = " + f4.toString());
System.out.println("f3 + f4 = " + f3.add(f4).toString());
System.out.println("f3 * f4 = " + f3.multiply(f4).toString() + "\n");
    }
}
------------------------------------------------<程式碼結束>--------------------------------------
附註:

沒有留言:

張貼留言