-1

所以这是我的分数课。数学有效,但我想减少分数。注意:这是在 Eclipse SDK Juno 中。

public class Fraction {
private int n, d;
public Fraction(int num, int denum){
    n = num;
    d = denum;
}

public int getNumerator(){
return n;
}
public void setNumerator(int num){
    n = num;
}
public int getDenumerator(){
    return d;
}
public void setDenumerator(int denum){
    d = denum;
}
**public void reduce(){
    int gcf = 1, smaller;
    if (n < d){
        smaller = n;
    }
    else{
        smaller = d;
    }
    for (int i = 1;i <= smaller; i++){
        if(n % i == 0 && d % i ==0){
            gcf = i;
        }
    }
    n = n/gcf;
    d = d/gcf;
    System.out.print(n + "/" + d);
}**
}

粗体字是我在 FractionMath 中输出的内容,如下所示。我不知道如何在这个类中应用 reduce 方法。我尝试了 method.Fraction() 但这给了我一个错误......帮助?

import java.util.*;

public class FractionMath {
public static void main(String[] args){
    Fraction f1, f2;
    Fraction ans = new Fraction(0,0);
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the numerator; then denumerator:\n");
    f1 = new Fraction(sc.nextInt(), sc.nextInt());
    System.out.print("Enter another numerator; and denumerator:\n");
    f2 = new Fraction(sc.nextInt(), sc.nextInt());
    System.out.print("Add (1)\nSubtract (2)\nMultiply (3)\nDivide (4)\n");
    int choice = sc.nextInt();
    if (choice == 1){
         if (f1.getDenumerator() == f2.getDenumerator()){
             ans.setNumerator(f1.getNumerator() + f2.getNumerator());
             ans.setDenumerator(f1.getDenumerator());
         }
         else{
             ans.setNumerator(f1.getNumerator() * f2.getDenumerator() + f2.getNumerator() * f1.getDenumerator());
             ans.setDenumerator(f1.getDenumerator() * f2.getDenumerator());
         }
    }
    else if (choice == 2){
        if (f1.getDenumerator() == f2.getDenumerator()){
             ans.setNumerator(f1.getNumerator() - f2.getNumerator());
             ans.setDenumerator(f1.getDenumerator());
         }
         else{
             ans.setNumerator(f1.getNumerator() * f2.getDenumerator() - f2.getNumerator() * f1.getDenumerator());
             ans.setDenumerator(f1.getDenumerator() * f2.getDenumerator());
         }
    }
    else if (choice == 3){
        ans.setNumerator(f1.getNumerator() * f2.getNumerator());
        ans.setDenumerator(f1.getDenumerator() * f2.getDenumerator());
    }
    else if (choice == 4){
        ans.setNumerator(f1.getNumerator() * f2.getDenumerator());
        ans.setDenumerator(f1.getDenumerator() * f2.getNumerator());
    }
}
}
4

1 回答 1

0

网上有很多解决方案。也许试试这个

于 2012-10-19T16:09:05.027 回答