java两个非常好的int被除掉,仍然返回0
尝试使用我的sumDanceScore方法,将我的danceScore数组中的每个元素除以sumDanceScore的返回值;然而,当它继续返回0时。我放置了println来表示有两个合法整数,但它总是==0,请帮助
package javasandbox;
import java.util.*;
public class JavaSandbox {
public static int sumDanceScore(int danceScore[], int first, int last)
{
if (first > last)
{
return 0;
}
else
{
int total = sumDanceScore(danceScore,first+1,last) + danceScore[first];
return total;
}
}
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Enter number of contestants : ");
int numContest = kbd.nextInt();
int danceScore[] = new int[numContest + 1];
int first = 0;
int last = danceScore.length - 1;
System.out.println("Enter dance scores: ");
int numContestIndex;
for (numContestIndex = 1; numContestIndex <= numContest; numContestIndex++)
{
danceScore[numContestIndex] = kbd.nextInt();
}
int danceScoreTotal = sumDanceScore(danceScore, first, last);
System.out.println("SUM DANCE SORE METHOD: "+danceScoreTotal);
for(int danceScoreIndex = 1; danceScoreIndex <= danceScore.length-1; danceScoreIndex++)
{
System.out.println("DANCE SCORE INDEX NUMBER: "+danceScore[danceScoreIndex]);
int danceScoreShare = danceScore[danceScoreIndex] / danceScoreTotal;
System.out.println("DANCER SHARE PERCENT: "+danceScoreShare);
}
}
}
# 1 楼答案
很明显,当我的danceScore数组中的每个元素除以
the bigger return value of sumDanceScore
时,由于int/int除法,返回值肯定是0规则说在分子/分母除法中, 如果分子<;分母,则由于int中的截断,结果将为0
例如:
解决方法是使用float/double作为除法变量的数据类型
# 2 楼答案
您需要先将
int
强制转换为浮点数(float
或double
)danceScoreShare
是一个分数,所以它也应该是float
或double
你的
danceScoreTotal
总是比danceScore[danceScoreIndex]
大,所以用java整数除法你总是会得到一个0的结果†实际上,你可以直接使用其中一个右手参数,而二进制数字升级会使用另一个参数
该technical details from the JLS
例如,使用除法
9 / 10
,可以看到|10 · 1| = 10
大于|9|
。因此它返回0