![](/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.