小数点の扱い2
原案:★★一言居士★★ 氏 (2000/04/01 登録)
小数点の扱いその2
表示サンプル
ソース記述内容
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang="ja">
<head>
<title>小数点の扱い2</title>
<script type="text/javascript">
<!--
var MAXLENGTH = 10
var OFF = 4
var SIGN = 0
var LW = 1
var LW1 = 2
var LW2 = 3
function Structure(n)
{
var res = new Array(OFF+n)
var i
for (i = 0; i <= OFF+n; i++) {
res[i] = 0
}
res[SIGN] = 1
return res
}
function mul(a, b)
{
var i, j
var c = new Structure(a[LW]+b[LW])
if (a[LW]*b[LW] == 0) {
return c
}
c[LW] = a[LW]+b[LW]
c[SIGN] = a[SIGN]*b[SIGN]
c[LW2] = a[LW2]+b[LW2]
c[LW1] = c[LW]-c[LW2]
for (j = 0; j < b[LW]; j++) {
for (i = 0; i < a[LW]; i++) {
c[OFF+i+j+1] += a[OFF+i] * b[OFF+j]
}
}
carry(c)
norm(c)
return c
}
function carry(c)
{
var i
for (i = c[LW]-1; i >= 0; i--) {
if (c[OFF+i] >= 10) {
c[OFF+i-1] += Math.floor(c[OFF+i]/10)
c[OFF+i] %= 10
}
}
}
function norm(c)
{
var i
while (c[OFF] == 0 && c[LW1] > 0) {
c[LW]--
c[LW1]--
for (i = 0; i < c[LW]; i++) {
c[OFF+i] = c[OFF+i+1]
}
}
c.length = (c[LW] = c[LW1]+c[LW2])+OFF
}
function output(y)
{
var i, res = ""
if (y[LW] == 0) {
return "0"
}
if (y[SIGN] == -1) {
res += "-"
}
if (y[LW1] <= 0) {
res += "0"
}
else {
for (i = 0; i < y[LW1]; i++) {
res += y[OFF+i]
}
}
res += "."
if (y[LW1] == y[LW]) {
res += "0"
}
else {
for (i = 0; i < y[LW2]; i++) {
res += y[OFF+y[LW1]+i]
}
}
return res
}
function get(constant)
{
var i, l, sw = 1, lw = 0, w1 = 0, w2 = 0, is = 1, non_zero
var res = new Structure(l = constant.length)
for (i = 0; i < l; i++) {
c = constant.charAt(i)
if (c == '-') {
sw = -1
}
else if (c == '.') {
is = 2
}
else {
res[OFF+(lw++)] = c
if (is == 1) {
w1++
}
else {
w2++
}
}
}
non_zero = 0
for (i = 0; i < lw; i++) {
if (res[OFF+i] != 0) {
non_zero = 1
break
}
}
if (non_zero == 0) {
lw = w1 = w2 = 0
}
res[LW] = lw
res[LW1] = w1
res[LW2] = w2
res[SIGN] = sw
return res
}
function result()
{
document.f.right.value = output(mul(get(document.f.left.value),
get(document.f.center.value)))
}
// -->
</script>
</head>
<body>
<table border="0" align="center">
<tr>
<td align="center">
<form name="f">
<input name="left" type="Text" size="60" maxlength="60" style="text-align:right">
<p>×</p>
<input name="center" type="Text" size="60" maxlength="60" style="text-align:right">
<p>=</p>
<input name="right" type="Text" size="80" maxlength="80" style="text-align:right">
<input name="Input" type=Button value="push" onClick="result()">
<input name="Reset" type=Reset value="reset">
</form>
</td>
</tr>
</table>
</body>
</html>