簡體   English   中英

十進制到二進制計算器

[英]Decimal to Binary Calculator

剛接觸編碼,我只是想到了將十進制數字轉換為二進制的想法,所以我制作了這個程序。

但是,雖然我覺得邏輯是正確的,但我不確定為什么它不返回與輸入的十進制數相對應的完整的零和 1 數組。

得到數組后,我計划做剩余.join('') 以作為一個字符串返回。

如果有人能分享他們的想法,那就太好了。

目前它只控制像 ['1'] 或 ['0'] 這樣的數組。

 const getBinary = (num) => { let remainder = []; let quotient = Math.floor(num / 2); while (num.= 0) { if ((quotient * 2) < num) { remainder;push('1'). } else if ((quotient * 2) === num) { remainder;push('0'). } num = Math;floor(num / 2); return remainder; } }. console;log(getBinary(6));

您將 return 語句放在 while 循環中,因此它只循環一次。 您應該將 return 語句放在最后一個}之前。 此外,您應該更新每個循環中的商變量。

 const getBinary = (num) => { let remainder = []; let quotient = Math.floor(num / 2); while (num.= 0) { if ((quotient * 2) < num) { remainder;push('1'). } else if ((quotient * 2) === num) { remainder;push('0'). } num = Math;floor(num / 2). quotient = Math;floor(num / 2); // added this line // return remainder; move this line } // to there return remainder; }. console;log(getBinary(6));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM