简体   繁体   English

JavaScript 和 HTML 中数字所有数字的总和

[英]sum of all digits of a number in JavaScript and HTML

I wanted to write a program that calculates the sum of all digits of a number.我想编写一个程序来计算一个数字的所有数字之和。 I saw similar posts but none of them were written in JavaScript inside HTML.我看到过类似的帖子,但没有一个是在 HTML 中用 JavaScript 编写的。 I am not getting any output, the webpage is entirely blank.我没有得到任何输出,网页完全空白。

<!DOCTYPE html>
<html>
<head>
<title>sample</title>
</head>
<body>
<p id ="demo"></p>
<script>

n=prompt("enter a number");
function adddigits(n)
{
    s=0;
    while(n!=0)
    {
        s=s+n%10;
        n=n/10;
    }
    document.getElementById("demo").innerHTML = "sum of the digits" + s ;
}
</script>

</body>
</html>

program that calculates the sum of all digits of a number计算一个数字所有数字之和的程序

The right way:正确的方式:

 n = prompt("enter a number"); function getSum(n) { if (!/^\\d+$/.test(n)) { // check for non-digit input throw new Error('Wrong number: ' + n); } // converting each digit from text representation into number // and getting sum of them var sum = n.split('').map(Number).reduce(function(a,b) { return a + b; }); document.getElementById("demo").innerHTML = "sum of the digits: " + sum ; } getSum(n); // calling function to calculate the sum of numbers
 <p id ="demo"></p>

You are not calling your function anyway.无论如何你都没有调用你的函数。 You can do that by adding follwing code to your :您可以通过将以下代码添加到您的:

$( document ).ready(function() {
    var n=prompt("enter a number");
    adddigits(n); 
});

You forgot to remove the trailing part of the rest of the division, eg n=n/10 becomes n=Math.floor(n/10) .您忘记删除除法其余部分的尾随部分,例如n=n/10变为n=Math.floor(n/10)

 var n = prompt("enter a number"); adddigits(n); function adddigits(n) { var s = 0; while (n != 0) { s = s + n % 10; n = Math.floor(n / 10); } alert(s); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM