有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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);
    }
} 

}


共 (2) 个答案

  1. # 1 楼答案

    很明显,当我的danceScore数组中的每个元素除以the bigger return value of sumDanceScore时,由于int/int除法,返回值肯定是0

    规则说在分子/分母除法中, 如果分子<;分母,则由于int中的截断,结果将为0

    int(smaller)/int(bigger_sum) ~= 0.some_value = 0 (in terms of result as int)
    

    例如:

    4/20 = 0.20(in double) = 0 (for int result).
    

    解决方法是使用float/double作为除法变量的数据类型

  2. # 2 楼答案

    您需要先将int强制转换为浮点数(floatdoubledanceScoreShare是一个分数,所以它也应该是floatdouble

    double danceScoreShare = (double)danceScore[danceScoreIndex] /  (double)danceScoreTotal;
    

    你的danceScoreTotal总是比danceScore[danceScoreIndex]大,所以用java整数除法你总是会得到一个0的结果

    实际上,你可以直接使用其中一个右手参数,而二进制数字升级会使用另一个参数

    technical details from the JLS

    ... the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|.

    例如,使用除法9 / 10,可以看到|10 · 1| = 10大于|9|。因此它返回0