-1
public static void main(String[] args) {
    int[] scores=new int[3];
    int[] total=new int[3];
    scores[0]=4;
    scores[1]=5;
    scores[2]=6;
    for(int z=0;z<3;z++){
        int num=scores[z];
        total[z]+=((num/5)*100);
        System.out.println(total[z]);
    }
}

I'm trying to assign value to total arrays in the loop, but output gives 0. I don't understand why it is like this.Can you help me?

pzr
  • 111
  • 2
  • 7

1 Answers1

1

In the first loop of this, num = 4 and then total[0] += ( (4/5) * 100 ) . The 4/5 is 0.8 but ints round down so it becomes 0. 0*100=0. 0 + 0 = 0. I think the second and 3rd prints would both give 100 though. (1 → 1 (times 100), 1.2 → 1 (times 100) )

This block below isn't code, but its showing where stuff is being pulled from and how it changes. Hopefully this better explains it.

for( int z = 0 ) {
int num = scores[z] = scores[0] = 4
total[z] += ( (num/5) * 100 ) = total[0] + ( (4/5) * 100 ) = 0 + ((int)0.8) * 100 = 0 + 0*100 = 0
}

for( z = 1 ) {
int num = scores[z] = scores[1] = 5
total[z] += ( (num/5) * 100 ) = total[1] + ( (5/5) * 100 ) = 0 + ((int)1) * 100 = 0 + 1*100 = 100
}

for( z = 2 ) {
int num = scores[z] = scores[2] = 6
total[z] += ( (num/5) * 100 ) = total[2] + ( (6/5) * 100 ) = 0 + ((int)1.2) * 100 = 0 + 1*100 = 100
}