![](/img/trans.png)
[英]Can someone explain to me why this nested loop function print this way?
[英]Can someone explain to me what is going on within this nested loop?
有人请解释下面的嵌套循环中发生了什么。 我在理解其工作方式时遇到了麻烦。
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);
}
嵌套for
循环将出现5次,将5个用户输入加到变量hoursWorked
。 指向所有这一切可能是要计算用户在该周中工作的小时数(每个星期中的每一天的每次迭代)。 然后通过将他的小时数乘以每小时的工资来获得他的薪水,并将其加到total
。
这非常简单,您可能唯一不了解的是:
hoursWorked = hoursWorked + stdin.nextInt();
它翻译成这样的东西:
new value of hoursWorked = old value of hoursWorked + userInput
它也可以写成:
hoursWorked += stdin.nextInt();
这段代码注释了每一步的操作:
//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.