首页 > 代码库 > 除法竖式
除法竖式
<script type="text/javascript">// ";}function printAlignRight(s, width){ print(" ".times(width - s.length) + s)}function div(dividendStr, divisorStr){ resultString = ""; dividend = parseInt(dividendStr); divisor = parseInt(divisorStr); if(isNaN(dividend) || isNaN(divisor) || divisor <= 0 || dividend <=0) return "输入数字,不能为0或负数"; dividendStr = dividend.toString(); divisorStr = divisor.toString(); if(dividendStr.length > 14) return "被除数太大" if(divisor > dividend) return "除数不能大于被除数" width = dividendStr.length + divisorStr.length + 3; quotient = Math.floor(dividend / divisor); quotientStr = quotient.toString(); print(" ".times(width - quotientStr.length) + quotientStr); print(" ".times(divisorStr.length + 1) + "-".times(dividendStr.length + 2)); print(divisorStr + " ) " + dividendStr); dividendPartStr = dividendStr.substring(0, dividendStr.length - quotientStr.length + 1); for(i = 0; i < quotientStr.length; i++) { alignWidth = width - quotientStr.length + i + 1; if(quotientStr[i] == "0") { if(i == quotientStr.length - 1) printAlignRight(dividendPartStr, alignWidth); else dividendPartStr = dividendPartStr + dividendStr[dividendStr.length - quotientStr.length + 1 + i]; continue; } product = divisor * parseInt(quotientStr[i]); productStr = product.toString(); if(i != 0) printAlignRight(dividendPartStr, alignWidth); printAlignRight(productStr, alignWidth); print(" ".times(divisorStr.length + 3) + "-".times(width - divisorStr.length - 3)); dividendPart = parseInt(dividendPartStr); difference = dividendPart - product; differenceStr = difference.toString(); if(i != quotientStr.length - 1) { if(difference == 0) differenceStr = "" dividendPartStr = differenceStr + dividendStr[dividendStr.length - quotientStr.length + 1 + i] } else print(" ".times(width - differenceStr.length) + differenceStr) } return resultString;}function compute(){ dividend = document.getElementById("dividend").value; divisor = document.getElementById("divisor").value; document.getElementById("result").innerHTML = div(dividend, divisor);}// ]]></script>
除 数: