问题描述
我正在编写一个程序以接收一个正数并分别输出每个数字。例如,如果输入为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