两个非常好的int被分割并仍然返回0

时间:2015-02-03 20:03:12

标签: java arrays for-loop recursion

尝试使用我的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 个答案:

答案 0 :(得分:1)

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

规则说在分子/分母中, 如果分子&lt;如果是分母,那么由于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作为除法变量的数据类型。

答案 1 :(得分:1)

您需要首先将int s转换为浮点数(floatdoubledanceScoreShare将成为一个分数,因此它也应该是floatdouble

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

您的danceScoreTotal将始终大于danceScore[danceScoreIndex],因此对于java整数除法,您将始终获得0结果。

实际上你只能施放一个右手参数而二进制数字促销就可以做另一个

technical details from the JLS

  

...为二进制数字提升(第5.6.2节)后的整数操作数n和d生成的商是一个整数值q,其大小尽可能大,同时满足| d·q | ≤| n |。

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