分隔数字的数字
Separating digits of a number
我正在编写一个程序来接收一个正数并分别输出每个数字。例如,如果输入是 692,程序应该输出 2, 9, 6.
我必须使用 while 循环并使用模运算符 (%) 分隔数字。
数字应该分开而不是将数字视为字符串并且以数学方式。
代码:
HTML
<div class="column1">
<div class="input">
<button onclick="problem_09()"> Run the program </button>
</div>
<strong><p id="output"> </p></strong>
</div>
JAVASCRIPT
function problem_09() {
var outputObj = document.getElementById("output");
var a = parseInt(prompt("Please enter a number: ", ""));
var digits = "";
while(a >= 0){
var d = a % 10;
outputObj.innerHTML= "number: "+a+"<br><br>its digits: " + d;
a = Math.floor(a/10);
}
outputObj.innerHTML = outputObj.innerHTML + "<br><br>" + "program ended";
document.getElementsByTagName("button")[0].setAttribute("disabled","true");
}
解决方法如下:
HTML:
<div class="column1">
<div class="input">
<button onclick="problem_09()"> Run the program </button>
</div>
<strong><div id="output"> </div></strong>
</div>
JS:
function problem_09() {
var outputObj = document.getElementById("output");
var a = parseInt(prompt("Please enter a number: ", ""));
var digit = "";
outputObj.innerHTML = ""
while(a > 0){
let num = a%10
a = Math.floor(a/10)
digit += "<p>"+num+"</p>"
}
outputObj.innerHTML = digit + "<br><br>" + "program ended";
document.getElementsByTagName("button")[0].setAttribute("disabled","true");
}
工作代码笔:https://codepen.io/TheKetan2/pen/rNLOrGR
输出:
从数学上讲,余数对 10 取模并除以 10。用简单的代码来说,
num = some number
while (num>0):
print(num%10)
num = num/10
我正在编写一个程序来接收一个正数并分别输出每个数字。例如,如果输入是 692,程序应该输出 2, 9, 6.
我必须使用 while 循环并使用模运算符 (%) 分隔数字。
数字应该分开而不是将数字视为字符串并且以数学方式。
代码:
HTML
<div class="column1">
<div class="input">
<button onclick="problem_09()"> Run the program </button>
</div>
<strong><p id="output"> </p></strong>
</div>
JAVASCRIPT
function problem_09() {
var outputObj = document.getElementById("output");
var a = parseInt(prompt("Please enter a number: ", ""));
var digits = "";
while(a >= 0){
var d = a % 10;
outputObj.innerHTML= "number: "+a+"<br><br>its digits: " + d;
a = Math.floor(a/10);
}
outputObj.innerHTML = outputObj.innerHTML + "<br><br>" + "program ended";
document.getElementsByTagName("button")[0].setAttribute("disabled","true");
}
解决方法如下:
HTML:
<div class="column1">
<div class="input">
<button onclick="problem_09()"> Run the program </button>
</div>
<strong><div id="output"> </div></strong>
</div>
JS:
function problem_09() {
var outputObj = document.getElementById("output");
var a = parseInt(prompt("Please enter a number: ", ""));
var digit = "";
outputObj.innerHTML = ""
while(a > 0){
let num = a%10
a = Math.floor(a/10)
digit += "<p>"+num+"</p>"
}
outputObj.innerHTML = digit + "<br><br>" + "program ended";
document.getElementsByTagName("button")[0].setAttribute("disabled","true");
}
工作代码笔:https://codepen.io/TheKetan2/pen/rNLOrGR
输出:
从数学上讲,余数对 10 取模并除以 10。用简单的代码来说,
num = some number
while (num>0):
print(num%10)
num = num/10