Java编写了一个计算击球平均数的方法,但没有给出正确的输出
我计算出的平均值每次都是0.0,而这是不应该的。任何帮助都将不胜感激 我的BaseballPlayer类中的代码:Java编写了一个计算击球平均数的方法,但没有给出正确的输出,java,methods,Java,Methods,我计算出的平均值每次都是0.0,而这是不应该的。任何帮助都将不胜感激 我的BaseballPlayer类中的代码: //BaseballPlayer parameters String name; int number; int singles; int doubles; int triples; int homeRuns; int atBats; int walks; int sacrificeFlies; //BaseballPlayer constructor method publ
//BaseballPlayer parameters
String name;
int number;
int singles;
int doubles;
int triples;
int homeRuns;
int atBats;
int walks;
int sacrificeFlies;
//BaseballPlayer constructor method
public BaseballPlayer(String name, int number, int singles, int triples, int homeRuns, int atBats, int walks,
int sacrificeFlies)
{
this.name = name;
this.number = number;
this.singles = singles;
this.triples = triples;
this.homeRuns = homeRuns;
this.atBats = atBats;
this.walks = walks;
this.sacrificeFlies = sacrificeFlies;
}
// Batting average
public double getBattingAverage() {
double average = ((singles+doubles+triples+homeRuns)/atBats);
return average;
}
我的主类中的代码:
BaseballPlayer player01 = new BaseballPlayer( "Mr. Business",13,12,13,4,84,63,7);
System.out.println(player01.getBattingAverage());
与此相反:
double average = ((singles+doubles+triples+homeRuns)/atBats);
试试这个:
double average = (double) (singles + doubles + triples + homeRuns) / atBats;
因为单打
,双打
,三打
,全垒打
,和atBats
的数据类型都是整数
,它在做数学运算,得到另一个整数
(“0”),然后将其存储为双打
(“0.0”),这不是您想要的。通过在前面添加(double)
,您可以指导JVM将结果转换为数据类型double
运行上面发布的代码,下面是我在本地看到的输出:
0.0
将结果转换为双精度后,我看到:
0.34523809523809523
为了得到更精确的结果而不是int,需要在计算过程中而不是在计算之后让JVM知道您想要什么。最简单的方法之一是将除数或红利转换为上述示例中的两倍。
i、 e
或
在原始代码中,该行为希望在整个计算完成后再次将结果从int转换为double(下面的代码部分可供参考)。精度已经降低,因此只能得到0而不是精确的数字:
double average = (double) ( (singles+doubles+triples+homeRuns)/ atBats);
谢谢你的帮助,我很感激!
double average = ( (singles + doubles + triples + homeRuns) / (double) atBats);
double average = (double) ( (singles+doubles+triples+homeRuns)/ atBats);