teamsalary = 600000 avgSalindivindiv = 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;
}
答案 0 :(得分:1)
你不能使用teamsalary = teamsalary - (numofpeople * avgSalindiv);
,因为这会在第一次减去0,第二次减去20000,第三次减去40000等等。你只想每次减去20000(每个人增加一次) )。您还需要保持变量名称的一致性。 (您同时使用avgSalindivindiv
和avgSalindiv
)
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
答案 1 :(得分:0)
我在逻辑中看到的唯一明显问题是以下几行:
teamsalary = teamsalary - (numofpeople * avgSalindiv);
在这里,您将减去平均工资乘以运行总人数,这是没有意义的。相反,您希望在循环的每次迭代期间减去相同的平均值avgSalindiv
。请尝试使用此代码:
int teamsalary = 600000;
int avgSalindivindiv = 20000;
int numofpeople = 0;
while (teamsalary >= 0) {
System.out.println(numofpeople);
teamsalary -= avgSalindiv;
++numofpeople;
}
答案 2 :(得分:0)
尝试删除break
,如下所示:
int teamsalary = 600000;
int avgSalindivindiv = 20000;
int numofpeople = 0;
while (teamsalary >= 0) {
System.out.println(numofpeople);
teamsalary = teamsalary - (numofpeople * avgSalindivindiv);
numofpeople++;
}