2016-09-25 75 views
-1

有人請解釋下面的嵌套循環內發生了什麼。我無法理解它是如何工作的。有人可以向我解釋這個嵌套循環內發生了什麼?

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

究竟它不明白嗎?變量的名稱應該是一個巨大的線索。 – chrylis

回答

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). 
} 
+0

這就是我正在尋找的,謝謝。 –

1

嵌套for循環itearting 5倍,5個用戶輸入求和以可變hoursWorked。指向這一切可能是計算用戶在那一週工作的小時數(每週的每一天的每次迭代)。然後通過將他的小時數乘以他每小時的薪水來獲得他的薪水,並將其添加到total

它是非常簡單的,你可能不知道的唯一的事情是:

hoursWorked = hoursWorked + stdin.nextInt();

它翻譯是這樣的:

new value of hoursWorked = old value of hoursWorked + userInput

它也可以寫爲:

hoursWorked += stdin.nextInt();

+0

究竟是什麼影響舊的工作小時數? numberOfTimesheets?從我看到的情況來看,第一個循環是收集薪資信息,第二個循環是計算? –

相關問題