有人请解释下面嵌套循环中发生的事情。我无法理解它是如何工作的。
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);
}
答案 0 :(得分:1)
嵌套for
循环迭代5次,将5个用户输入汇总到变量hoursWorked
。指向所有这些可能是计算用户在该周工作的小时数(每周的每一天的每次迭代)。然后通过将他的小时数乘以他/小时的工资来获得他的工资,并将其添加到total
。
这很简单,你可能唯一不理解的是:
hoursWorked = hoursWorked + stdin.nextInt();
它转换为类似的东西:
new value of hoursWorked = old value of hoursWorked + userInput
它也可以写成:
hoursWorked += stdin.nextInt();
答案 1 :(得分:1)
这是代码评论它在每一步所做的事情:
//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).
}