2017年4月7日金曜日

開発環境

Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)のPart 1(Starting with the basics)、Chapter 5(Iteration)の Boolean functions の Exercise 6-1.を JavaScript で取り組 んでみる。

Exercise 6-1.

コード(Emacs)

HTML5

a = <input id="a0" type="number" min="1" step="1" value="100">
<button id="run0">run</button>
<button id="clear0">clear</button>
<pre id="output0"></pre>

<script src="sample1.js"></script>

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    input_a = document.querySelector('#a0'),
    pre0 = document.querySelector('#output0');

let sqrt = (a) => {
    let x = 1;
    while (true) {
        let y = (x + a / x) / 2;
        if (y === x) {
            break;
        }
        x = y;
    }
    return x;
};

let output = () => {
    let a = parseInt(input_a.value, 10);

    let x = sqrt(a),
        y = Math.sqrt(a),
        diff = Math.abs(x - y);

    pre0.textContent = `a sqrt(a) Math.sqrt(a) diff\n` +
        `${a} ${x} ${y} ${diff}\n`;
};
    

btn0.onclick = output;
btn1.onclick = () => {
    pre0.textContent = '';
};

pre0.textContent += `a sqrt(a) Math.sqrt(a) diff\n`;
for (let i = 1; i < 10; i += 1) {
    let x = sqrt(i),
        y = Math.sqrt(i),
        diff = Math.abs(x - y);

    pre0.textContent += `${i} ${x} ${y} ${diff}\n`;
}
a =













						

0 コメント:

コメントを投稿