2017-04-15 49 views
0

我正在編寫一些代碼(javascript)將基數10的數字更改爲基數16.如果餘數介於10和15之間,我知道基數16有字母。我有麻煩。我無法將剩下的部分改成這封信。我想將基數10的數字改爲基數16

到目前爲止我有:

var mynum = 4053,remainder=[]; 
 

 
while (mynum > 0) { 
 

 
    total = mynum % 16; 
 
    remainder.push(total); 
 
    mynum = Math.floor(mynum/16); 
 

 
    switch (total > 9 || total < 16) { 
 
    case total === 10: 
 
     total = "A"; 
 
     break; 
 
    case total === 11: 
 
     total = "B"; 
 
     break; 
 
    case total === 12: 
 
     total = "C"; 
 
     break; 
 
    case total === 13: 
 
     total = "D"; 
 
     break; 
 
    case total === 14: 
 
     total = "E"; 
 
     break; 
 
    case total === 15: 
 
     total = "F"; 
 
     break; 
 
    } 
 

 
} 
 

 
console.log(total,remainder)

比方說, 「myNum的」= 4053,然後我會得到5,13,​​15。但我想得到5,D,F。我也嘗試過使用「for」循環,但得到了同樣的結果。這感覺就像我很接近,但只是錯過了一些東西,有人可以幫我嗎?

myNum的是實際數量,總的是餘數,「剩女」是我把其餘的在列表

+0

我給你做,你可能做太多的片段。 – mplungjan

+0

'十六進制= 4053..toString(16);' –

回答

1

hexString = yourNumber.toString(16);是一種更好的方式來做到這一點。但是通過代碼中的邏輯,這裏就是你錯誤的地方。

這個remainder.push(total);聲明應該在switch之後。在你的代碼中,它是在switch之前。

mynum = 4053; 
 
remainder = []; 
 

 
while (mynum > 0){ 
 

 
    total = mynum % 16; 
 
    mynum = Math.floor(mynum/16); 
 

 
    // remainder.push(total); 
 

 
    switch (total > 9 || total < 16){ 
 
     case total === 10: 
 
      total = "A"; 
 
      break; 
 
     case total === 11: 
 
      total = "B"; 
 
      break; 
 
     case total === 12: 
 
      total = "C"; 
 
      break; 
 
     case total === 13: 
 
      total = "D"; 
 
      break; 
 
     case total === 14: 
 
      total = "E"; 
 
      break; 
 
     case total === 15: 
 
      total = "F"; 
 
      break; 
 
\t } 
 
    remainder.push(total); // here 
 
} 
 

 
console.log(remainder);

+0

謝謝。小事情有很大的不同。 –

1
hexString = yourNumber.toString(16); 

它會轉換基地10臺16

相關問題