【问题标题】:How can i assign value to the index of the arrays in the loop in Java? [duplicate]如何为Java循环中的数组索引赋值? [复制]
【发布时间】:2021-07-27 08:24:17
【问题描述】:
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]);
    }
}

我正在尝试为循环中的总数组赋值,但输出为 0。我不明白为什么会这样。你能帮帮我吗?

【问题讨论】:

    标签: java arrays loops class


    【解决方案1】:

    在第一个循环中,num = 4,然后是total[0] += ( (4/5) * 100 ) 。 4/5 为 0.8,但整数向下舍入,因此变为 0。0*100=0。 0 + 0 = 0。我认为第二次和第三次打印都会给出 100。 (1 → 1 (乘以 100), 1.2 → 1 (乘以 100))

    下面的这个块不是代码,但它显示了从哪里提取东西以及它是如何变化的。希望这能更好地解释它。

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 2016-01-17
      • 2020-08-15
      • 2017-11-20
      • 2021-12-01
      • 2021-11-08
      相关资源
      最近更新 更多