let a number=153 我們將如何拆分這 3 個數字 n1,n2,n3 我試過了-:
let n = 153
let n1 = n % 10;
let n2 = ((n - n1) / 10) % 10;
let n3 = ((n - n1)/10)/10;
我得到 n1 & n2 正確但找不到 n3 請回答
uj5u.com熱心網友回復:
你需要做
const n = 153;
let n1 = n % 10;
let n2 = ((n - n1) / 10) % 10;
let n3 = ((((n - n1) / 10) - n2) / 10) % 10;
console.log(n1, n2, n3)
更容易就像 - 但這確實改變了 n 當然
let n = 153;
let n1 = n % 10;
n = (n - n1) / 10;
let n2 = n % 10;
n = (n - n2) / 10;
let n3 = n % 10;
console.log(n1,n2,n3)
或者如果你想有創意
const n = 153;
const [n1, n2, n3] = ((n) => Array.from({length: Math.floor(Math.log10(n)) 1}, (_, i) => Math.floor(n / (10**i)) % 10))(n);
console.log(n1, n2, n3)
uj5u.com熱心網友回復:
你可以把它們變成一個字串,拆分字串并映射回這樣的數字
const number = 153
const [n3, n2, n1] = String(number).split('').map(Number)
console.log(n1, n2, n3)
uj5u.com熱心網友回復:
是正確的n3,只是它回傳十進制數字。AparseInt會做必要的事
let n=$('#armstrong')[0].value;
let n1 = n % 10;
let n2 = ((n - n1) / 10) % 10;
let n3 = parseInt(((n - n1)/10)/10);
if(Math.pow(n1,3) Math.pow(n2,3) Math.pow(n3,3)===parseInt(n))
console.log(n ' Is Armstrong');
else
console.log(n ' Is not Armstrong');
$('#armstrong').on('input',function(){
let n=this.value;
let length_n=('' n).length;
var sum=0;
for(var i=0;i<length_n;i )
{
sum =Math.pow(('' n)[i],length_n);
}
if(sum===parseInt(n))
console.log(n ' Is Armstrong');
else
console.log(n ' Is not Armstrong');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="armstrong" value="153">
參考
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494251.html
標籤:javascript
上一篇:如何從id串列中單擊一個id?
