我试图为我的一个编码挑战计算给定分数的排名,但我对我收到的输出很感兴趣。
我必须为给定的分数创建主板(假设分数是按顺序排列的array )。我创造了一种方法,它给出了给定分数的等级,
private static int[] assignCurrentRanks(int[] scores) {
int[] currentRanks=new int[scores.length];
currentRanks[0]=1;//by default the first score will be rank 1
for(int i=1;i<currentRanks.length;i++) {
currentRanks[i]=(scores[i]==scores[i-1])?currentRanks[i-1]:++currentRanks[i-1];
System.out.println("Inside the loop : ["+i+"] "+scores[i]+" "+currentRanks[i]);
}
return currentRanks;
}示例输入: 100,100,50,40,40,20,10
预期排名: 1,1,2,3,3,4,5
我可以看到,在循环过程中已经正确地分配了秩,当我在主方法中打印秩之后,返回的数组是不同的。
我知道逻辑有问题,但我找不到。请帮帮忙!!
下面是我的main方法,
public static void main(String[] args) {
int[] scores=new int[]{100,100,50,40,40,20,10};
int[] currentRanks=assignCurrentRanks(scores);
System.out.println("Printing after the loop");
for(int i=0;i<scores.length;i++)
System.out.println("["+i+"]"+scores[i]+" "+currentRanks[i]);
}我得到的是
//index 0 is already assigned with 1 by default
Inside the loop : [1] 100 1
Inside the loop : [2] 50 2
Inside the loop : [3] 40 3
Inside the loop : [4] 40 3
Inside the loop : [5] 20 4
Inside the loop : [6] 10 5
Printing after the loop
[0]100 1
[1]100 2
[2]50 3
[3]40 3
[4]40 4
[5]20 5
[6]10 5发布于 2018-08-06 15:29:51
++currentRanks[i-1];\\this increments the value of array element i-1
您会增加循环中使用的优先级别,从而产生意想不到的行为。应将预期的行为更改为:
currentRanks[i]=(scores[i]==scores[i-1])?currentRanks[i-1]:currentRanks[i-1] + 1;
发布于 2018-08-06 15:29:35
很可能是++currentRanks[i-1]正在改变结果。
试一试:
currentRanks[i]=(scores[i]==scores[i-1])?currentRanks[i-1]:currentRanks[i-1]+1;https://stackoverflow.com/questions/51710890
复制相似问题