[英]Unexpected results of integer/double interaction - zero is returned after the division operation
我对“ documentLength”变量有疑问。 当我将参数输入到方法中时,它是93。但是由于某种原因,它会更改。 输入参数也是一个int变量。
我将这个类称为Word,然后将其从main中的checkWord类中的职业中的方法称为:
double occupation = word.get(1).occupationOfDocument(documentLength); // line 83 in run-time below
职业文档
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
}
我收到以下运行时错误:
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学生需要帮助
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;
将会产生适当的结果。 了解有关类型转换和类型扩展以获得更多上下文的更多信息。
您在第一种情况下进行整数除法,这意味着例如4/3 = 1
,在您的情况下为24/93 = 0
如果要使其为双24/93 = 0
则需要在int值上添加24/93 = 0
:
double occupation = (((double)(length * occurances))/((double)documentLength))*100;
应该是安全的。 至于第二个错误,您明确告诉程序
documentLength = this.documentLength; //this.documentLength = 0 as you defined above
double occupation = ((length * occurances)/documentLength)*100;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.