2016-09-16 159 views
-2

任何人都可以解釋這個while循環對我嗎?它是免費代碼營羅馬數字挑戰的一部分 - 這不是我的,我做了我自己的,但它是更多的代碼。我試圖理解這一點來改善我自己。無論如何,while循環完全拋棄了我。任何幫助都是極好的。while循環javascript邏輯

function romans(num){ 
    var roman = ""; 
    var romanNumerals = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]; 
    var numbers = [1000,900,500,400,100,90,50,40,10,9,5,4,1]; 

    for (var i=0; i<numbers.length; i++) { 
     //If the num was 5 then then it would read 5 greater than 1000? 
     while (num >= numbers[i]) { 
      roman = roman + romanNumerals[i] 
      //5 minus 1000? 
      num = num - numbers[i] 
     } 
    } 

    return roman; 
} 

console.log(romans(5)) 
+0

'// 5減去1000?'只有當數學被完全破壞並且5> = 1000'纔會是真的:)對於' num === 5''while'循環只會爲'i === 10'執行一次' – Andreas

回答

1

num開始爲所需的輸入,然後你發現,加起來num開始,最大的羅馬數字(numbers[0])的數字。

您與while循環重複,因爲你可能需要的信的多個副本(即"III" == 3

romans(5)不會觸發while循環,直到numbers[10](因爲你說5 >= 1000 == false)在這一點上,你追加字符V到roman,從num減去5。 while循環將不會再次觸發,因爲num現在爲0.

試着用romans(3001)來思考它,你會看到M/1000的while循環觸發3次,然後跳過10次,然後觸發一次I/1

+1

Dangit im slow:'( – namlik

1

function romans(num){ 
 
var roman = ""; 
 
var romanNumerals=["M","CM","D","CD","C","XC","L","XL","X", 
 
"IX","V","IV","I"]; 
 
var numbers = [1000,900,500,400,100,90,50,40,10,9,5,4,1]; 
 

 
for (var i=0; i<numbers.length; i++){ 
 

 
    //If the num was 5 then then it would read 5 greater than 1000? 
 
    console.log("comparing: " + numbers[i]); 
 
    console.log(" with: " + num); 
 
    while(num >= numbers[i]){ 
 
    console.log("entered"); 
 
     roman = roman + romanNumerals[i] 
 
     //5 minus 1000? 
 
     num = num - numbers[i] 
 
     console.log('subtracting: ' + numbers[i]); 
 
     } 
 
    } 
 
    return roman 
 
} 
 
console.log(romans(44))

,直到它找到一個較小它會下去號線:例如44:

在它會去ŧ通過數組數組,直到它找到一個數字然後44(在while循環從未進入的迭代期間)。

當它找到一個小於44的數字時,它進入while循環,並在該迭代中獲得位置i處的romanNumerals,在這種情況下爲40.然後它將原始數字降低40(44-40 = 4)然後退出循環返回搜索一個低於4的數字。