有 Java 编程相关的问题?

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

while循环和打印列表中的Java减量变量

团队工资=600000 AVGSALINDIVIV=20000

如果一个团队的预算是600000,平均个人工资是20000,那么他们可以雇佣多少团队成员

我想打印一个如下所示的列表:

0
1
2
3
...all the way to 30

以下是迄今为止我的代码,它不起作用:

int teamsalary = 600000;
int avgSalindivindiv = 20000;
int numofpeople = 0;
while(teamsalary >= 0) {
    System.out.println(numofpeople);
    teamsalary = teamsalary - (numofpeople * avgSalindiv);
    numofpeople++;
    break;
}

共 (3) 个答案

  1. # 1 楼答案

    尝试删除break,如下所示:

    int teamsalary = 600000;
    int avgSalindivindiv = 20000;
    int numofpeople = 0;
    while (teamsalary >= 0) {
        System.out.println(numofpeople);
        teamsalary = teamsalary - (numofpeople * avgSalindivindiv);
        numofpeople++;
    }
    
  2. # 2 楼答案

    我看到你的逻辑中唯一明显的问题是以下几行:

    teamsalary = teamsalary - (numofpeople * avgSalindiv);
    

    在这里,你将平均工资乘以总人数,这是没有意义的。相反,您希望在循环的每次迭代中减去相同的平均值avgSalindiv。请尝试改用以下代码:

    int teamsalary = 600000;
    int avgSalindivindiv = 20000;
    int numofpeople = 0;
    while (teamsalary >= 0) {
        System.out.println(numofpeople);
        teamsalary -= avgSalindiv;
        ++numofpeople;
    }
    
  3. # 3 楼答案

    您不能使用teamsalary = teamsalary - (numofpeople * avgSalindiv);,因为这将第一次减去0,第二次减去20000,第三次减去40000,等等。您只需每次减去20000(对于每个添加的人)。您还需要保持变量名的一致性。(您同时使用了avgSalindivindivavgSalindiv

    int teamsalary = 600000;
    int avgSalindivindiv = 20000;
    int numofpeople = 0;
    System.out.println(numofpeople);
    
    // subtracting avgSalindivindiv here prevents loop from running an extra time
    while((teamsalary-=avgSalindivindiv) >= 0) {
        numofpeople++;
        System.out.println(numofpeople);
    }
    

    输出:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30