在 JavaScript 中查詢數字各位的乘積
我們需要編寫一個 JavaScript 程式,該程式接收一個數字並找到其所有數字的乘積。
輸入輸出場景
假設有一個數字分配給一個變數,任務是找到該數字的乘積。
Input = 12345; Output = 120
讓我們看看另一個場景,我們將字串數字轉換為整數值並將其相乘。
Input = "12345"; Output = 120
Math.floor()
Math.floor() 函式在 JavaScript 中返回小於等於給定數字的最大整數。簡單來說,此方法將數字向下舍入到最接近的整數。以下是Math.floor() 方法的語法:
Math.floor(x)
為了更好地理解,請考慮以下程式碼片段,在這裡我們為該方法提供各種輸入值。
Math.floor(10.95); // 10 Math.floor(10.05); // 10 Math.floor(10) // 10 Math.floor(-10.05); // -10 Math.floor(-10.95); // -1
示例 1
數字各位的乘積
在下面的示例中,我們有一個變數num儲存 12345,我們建立了另一個變數 product 來儲存數字的乘積(最初設定為 1)。
當num不為 0 時,num 將除以 10,結果儲存在product中。這裡使用 Math.floor() 來消除最後一位數字。
<!DOCTYPE html> <html> <title>Product of number digits</title> <head> <p id = "para"></p> <script> var num = 12345; var product = 1; function func(){ while (num != 0) { product = product * (num % 10); num = Math.floor(num / 10); } document.getElementById("para").innerHTML = "The productduct of number digits is: " + product; }; func(); </script> </head> </html>
parseInt()
parseInt() 函式將解析字串引數並返回一個整數值。
語法
以下是語法:
parseInt(string)
為了更好地理解,請考慮以下程式碼片段,在這裡我們為該方法提供各種輸入值。
parseInt("20") // 20 parseInt("20.00") // 20 parseInt("20.23") // 20
示例
將字串數字轉換為整數
在下面的示例中,我們定義了一個字串,其中包含一個整數值12345。使用 for 迴圈,我們遍歷字串的每個字元,使用parseInt()方法將其轉換為整數值,並將結果值乘以一個變數(product:初始化為 1)。
<!DOCTYPE html> <html> <head> <title>Product of Number digits</title> <button onClick = "func()">Click me! </button> <p id = "para"> </p> <script> function func(){ let string = "12345"; let product = 1; let n = string.length; for (let x = 0; x < n; x++){ product = product * (parseInt(string[x])); } document.getElementById("para").innerHTML = product; }; </script> </head> </html>
示例
使用建構函式
在此示例中,我們建立了一個類的建構函式,並在建構函式內部,我們使用this關鍵字來呼叫立即物件,稍後我們將使用prompt()函式從使用者那裡獲取輸入。建立另一個變數pro來儲存數字的乘積。最初將其設定為 1。當變數num的值不為 0 時,它將除以 10,結果儲存在變數pro中。在這裡,我們使用Math.floor()方法來消除最後一位數字。
<!DOCTYPE html> <html> <head> <title>Product of digits</title> </head> <body> <script> class Sum { constructor() { this.pro = 1; this.n = prompt("Enter a number:"); while (this.n != 0) { this.pro = this.pro * (this.n % 10); this.n = Math.floor(this.n / 10); } } } const res = new Sum(); document.write("Sum of Digit is = " + res.pro); </script> </body> </html>
廣告