[英]Can someone explain to me what is going on within this nested loop?
Someone please explain what is going on within the nested loop below. 有人请解释下面的嵌套循环中发生了什么。 I'm having trouble understanding how it works.
我在理解其工作方式时遇到了麻烦。
int numberOfTimesheets;
int centsPerHour = 0;
int hoursWorked;
total = 0;
numberOfTimesheets = stdin.nextInt();
for(int i = 1; i <= numberOfTimesheets; i++){
hoursWorked = 0;
centsPerHour = stdin.nextInt();
for (int ii = 1; ii <= 5; ii++){
hoursWorked = hoursWorked + stdin.nextInt();
}
total = total + (hoursWorked * centsPerHour);
}
Nested for
loop is itearting 5 times, summing 5 user inputs to variable hoursWorked
. 嵌套
for
循环将出现5次,将5个用户输入加到变量hoursWorked
。 Point to all this is probably to count number of hours the user worked in that week (each iteration for each day of the week). 指向所有这一切可能是要计算用户在该周中工作的小时数(每个星期中的每一天的每次迭代)。 Then get his salary by multiplying his hours by his pay per hour, and add it to
total
. 然后通过将他的小时数乘以每小时的工资来获得他的薪水,并将其加到
total
。
It's pretty straightforward, the only thing you may not understand is: 这非常简单,您可能唯一不了解的是:
hoursWorked = hoursWorked + stdin.nextInt();
It translates to something like this: 它翻译成这样的东西:
new value of hoursWorked = old value of hoursWorked + userInput
It can also be written as: 它也可以写成:
hoursWorked += stdin.nextInt();
This is the code commented with what it is doing at each step: 这段代码注释了每一步的操作:
//go through each time sheet
for(int i = 1; i <= numberOfTimesheets; i++){
hoursWorked = 0; // reset the number of hours worked (presumably for that week).
centsPerHour = stdin.nextInt(); //get the wage of the current timesheet
//go through each day for the current timesheet
for (int ii = 1; ii <= 5; ii++){
hoursWorked = hoursWorked + stdin.nextInt(); //add up the number of hours worked in that week
}
total = total + (hoursWorked * centsPerHour); //add the amount of money made this week to their current total (salary).
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.