木曜日, 4月 16, 2026

Let's start JavaScript 101 
シンプルな三角関数計算機

HTMLでシンプルな三角関数計算機を作ってみました。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>三角関数計算機</title>
<style>
body {
font-family: "Segoe UI", sans-serif;
background: gray;
display: flex;
justify-content: center;
align-items: center;
height: 30vh;
margin: 0;
color: white;
}

input, button {
font-size: 16px;
margin: 5px;
}

</style>
</head>
<body>
<center>
<h3>三角関数計算機</h3>

<input type="number" id="angle"
    placeholder="角度(度)を入力">
<br>

<button onclick="calc('sin')">sin</button>
<button onclick="calc('cos')">cos</button>
<button onclick="calc('tan')">tan</button>
<button onclick="calc('asin')">asin</button>
<button onclick="calc('acos')">acos</button>
<button onclick="calc('atan')">atan</button>

<h3 id="result">結果: </h3>

<script>
function calc(type) {
const deg =
       parseFloat(document.getElementById("angle").value);

if (isNaN(deg)) {
document.getElementById("result").textContent =
        "数値を入力してください";
return;
}

// 度 → ラジアン変換
const rad = deg * Math.PI / 180;

let value;

if (type === "sin") value = Math.sin(rad);
if (type === "cos") value = Math.cos(rad);
if (type === "tan") value = Math.tan(rad);
if (type === "asin") value = Math.asin(rad);
if (type === "acos") value = Math.acos(rad);
if (type === "atan") value = Math.atan(rad);

document.getElementById("result").textContent =
`結果: ${type}(${deg}°) = ${value.toFixed(6)}`;
}
</script>
</center>
</body>
</html>

実行したら・・・

角度を入力し、三角関数ボタンをクリックするだけです。

sin cos tanの結果。

asin acos atanの結果。
asinとacosがNaNなのは、Not a Numberの略で数値ではない非数を示す浮動小数点数の特殊な値です。