整数/双重交互的意外结果 - 在除法运算后返回零

时间:2016-10-07 18:51:44

标签: java variables methods

我对" documentLength"有一个问题。变量。 当我将参数输入到方法中时,它是93.但由于某种原因它会改变。输入参数也是一个int变量。

我调用了Word类,其中的方法就是来自类的checkWord中的OccupOfDocument,如下所示:

double occupation = word.get(1).occupationOfDocument(documentLength); // line 83 in run-time below

occupationOfDocument看起来像这样

public double occupationOfDocument(int documentLength){
    int length = getLength(); //equals 8 when I run the program
    int occurances = getOccurances(); //equals 3 when I run the program
    System.out.println(documentLength); //Prints 93 as expected

    double occupation = ((length * occurances)/documentLength)*100; //equals 0 somehow (probably division by)

    return occupation; //expected around 25.8
}

此方法返回" 0",但如果我将代码更改为此,

private int documentLength = 0;
public double occupationOfDocument(int documentLength){
    int length = getLength(); //equals 8 when I run the program
    int occurances = getOccurances(); //equals 3 when I run the program
    documentLength = this.documentLength;
    System.out.println(documentLength); //Prints 0 somehow

    double occupation = ((length * occurances)/documentLength)*100; //equals 0 somehow (probably divisjon by 0)

    return occupation; //expected around 25.8
}

我收到以下RUN-TIME错误:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Word.occupationOfDocument(Word.java:44)
    at checkWord.main(checkWord.java:83)

Word.java:44     这是数学的一行,我宣布和初始化职业

我知道它说我要除以0.我只是不明白它是如何发生的。

如果我输入数字而不是变量" documentLength",脚本会按预期执行

感谢您的帮助;)

需要帮助的IT学生

2 个答案:

答案 0 :(得分:3)

public double occupationOfDocument(int documentLength){
  int length = getLength(); //equals 8 when I run the program
  int occurances = getOccurances(); //equals 3 when I run the program
  System.out.println(documentLength); //Prints 93 as expected

  double occupation = ((length * occurances)/documentLength)*100; //equals 0 somehow (probably division by)

  return occupation; //expected around 25.8

}

在这里,你将8乘以3并得到24,然后你将整数除以93 - 这就得到0。

如果您修改

double occupation = ((double) (length * occurances)/documentLength)*100; 

将产生适当的结果。详细了解type conversion and type widening以获取更多背景信息。

答案 1 :(得分:0)

你在第一个场景中进行整数除法,例如4/3 = 1,在你的情况下是24/93 = 0,如果你想把它作为一个double,你需要为int值添加一个强制转换:

double occupation = (((double)(length * occurances))/((double)documentLength))*100;

应该是安全的。至于你明确告诉程序

的第二个错误

documentLength = this.documentLength; //this.documentLength = 0 as you defined above

double occupation = ((length * occurances)/documentLength)*100;