首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java中的小数加、减、乘、除

Java中的小数加、减、乘、除
EN

Stack Overflow用户
提问于 2015-11-08 02:08:02
回答 1查看 6.1K关注 0票数 0

我正在尝试在Java中对分数进行加法、乘法和除法。我得到的输出是: FRACTIONS@3d4eac69。有什么想法吗?

代码语言:javascript
复制
public class FRACTIONS {
private int numer, denom;
    public FRACTIONS (){
    numer=1;
    denom=1;
}
public FRACTIONS (int n, int d){
    numer=n;
    denom=d;
}
public int getNumerator(){
    return numer;
}
public int getDenominator (){
    return denom;
}
public FRACTIONS add(FRACTIONS other){
    int n = numer * other.denom + other.numer * denom;
    int d = denom * other.denom;
    return new FRACTIONS (n, d);
}

public FRACTIONS sub(FRACTIONS other){
int n = numer * other.denom + other.numer * denom;
int d = denom * other.denom;
return new FRACTIONS (n, d);
}

public FRACTIONS mult(FRACTIONS other){
int n = numer * other.numer;
int d = denom * other.denom;
return new FRACTIONS (n, d);
}

public FRACTIONS div(FRACTIONS other){
int n = numer * other.denom;
int d = denom * other.numer;
return new FRACTIONS (n, d);
}

public String toString(){
String str;
str= n + " / " + d;
return str;
}

}

测试仪程序:

代码语言:javascript
复制
import java.util.Scanner;
public class FRACTIONS_TESTER {

public FRACTIONS_TESTER() {
}

public static void main(String[] args) {
    Scanner reader = new Scanner (System.in);
    Scanner scan = new Scanner (System.in);
    FRACTIONS numer, denom;
    numer= new FRACTIONS();
    denom = new FRACTIONS ();
    System.out.print ("Enter the numerator for fraction 1: ");
    int n1 = reader.nextInt();
    System.out.print ("Enter the denominator for fraction 1: ");
    int d1 = reader.nextInt();
    System.out.print ("Enter the numerator for fraction 2: ");
    int n2 = reader.nextInt();
    System.out.print ("Enter the denominator for fraction 2: ");
    int d2 = reader.nextInt();
int n = 5;
int d = 6;
    FRACTIONS f1=new FRACTIONS (n1, d1);
    FRACTIONS f2=new FRACTIONS (n2, d2);
    FRACTIONS f3=new FRACTIONS (n,d);


    int opt;
    System.out.println ("Select the corresponding number for the desired 
 operation: ");
    System.out.println (" 1.  Addition \n 2.  Subtraction \n 3. 
 Multiply \n 4.  Divison");
    opt=scan.nextInt();
    if (opt==1){
        f3=f1.add (f2);

    }
    if (opt==2){
        f3=f1.sub (f2);

    }
    if (opt==3) {
        f3=f1.mult (f2);

    }
    if (opt==4){
        f3=f1.div (f2);

    }
    }
 System.out.println (f3);
}

提前谢谢。我只希望输出是以"/“形式返回的字符串

EN

回答 1

Stack Overflow用户

发布于 2015-11-08 02:10:54

ndtoString的作用域中未定义。也许你的意思是

代码语言:javascript
复制
@Override
public String toString() {
    return numer + " / " + denom;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33586031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档