javascript 二乗、三乗等の累乗の値を計算する

javascript 二乗、三乗等の累乗の値を計算する

javascriptでmathオブジェクトのpowメソッドを使用して二乗、三乗といった累乗の値を計算するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 102.0.5005.63

powメソッド使い方

powメソッドを使うと累乗の計算を行うことが可能です。

Math.pow(底,指数)

指数にマイナスを指定すると
x-1 = 1 / x
x-2 = 1 / x2
x-3 = 1 / x3
.
.
x-n = 1 / xn
となり、

分数を指定すると
x1/2 = xの平方根
x1/3 = xの3乗根
.
.
x1/n = xのn乗根
xm/n = (xのn乗根)m
となります。

powメソッド使い方

console.log(Math.pow(2,2)); // 2の2乗 結果 4

console.log(Math.pow(2,3)); // 2の3乗 結果 8

console.log(Math.pow(3,2)); // 3の2乗 結果 9

console.log(Math.pow(2,0)); // 2の0乗 結果 1

console.log(Math.pow(-3,3)); // -3の3乗 結果 -27

console.log(Math.pow(2,-1)); // 1 / 2(2×1) 結果 0.5

console.log(Math.pow(2,-2)); // 1 / 4(2×2) 結果 0.25

console.log(Math.pow(2,0.5)); // 2の2乗根 √2のこと 結果 1.4142135623730951

サンプルコード

以下は、テキストフォームに入力した数値を、 別のテキストフォームに累乗の値を計算して出力するだけのサンプルコードとなります。

※cssには「uikit」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- UIkit CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.5.5/dist/css/uikit.min.css" />

  <!-- UIkit JS -->
  <script src="https://cdn.jsdelivr.net/npm/uikit@3.5.5/dist/js/uikit.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/uikit@3.5.5/dist/js/uikit-icons.min.js"></script>
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 20px;
  }
</style>
<script>

  function cal() {

    //テキストボックス底の値を取得
    let val1 = document.getElementsByName("text-box")[0].value;

    //テキストボックス指数の値を取得
    let val2 = document.getElementsByName("text-box2")[0].value;
    
    //累乗の値を計算して表示
    document.getElementsByClassName("text-box-class")[0].value = Math.pow(val1, val2);

  }

</script>

<body>
  <div class="main">
    <div class="uk-light uk-background-secondary uk-padding">

      <form>
        <fieldset class="uk-fieldset">
          <legend class="uk-legend">累乗</legend>
          <div class="uk-margin">
            <input id="text-box3" name="text-box3" class="uk-input text-box-class" type="text" placeholder="Input">
          </div>
        </fieldset>
      </form>

      <form>
        <fieldset class="uk-fieldset">
          <legend class="uk-legend">底</legend>
          <div class="uk-margin">
            <input id="text-box" name="text-box" class="uk-input" type="number" placeholder="Input">
          </div>
        </fieldset>
      </form>

      <form>
        <fieldset class="uk-fieldset">
          <legend class="uk-legend">指数</legend>
          <div class="uk-margin">
            <input id="text-box2" name="text-box2" class="uk-input" type="number" placeholder="Input">
          </div>
        </fieldset>
      </form>

      <p uk-margin>
        <button class="uk-button uk-button-danger" onclick="cal()">計算</button>
      </p>

    </div>
  </div>
</body>

</html>

累乗の値が計算されて出力されていることが確認できます。