没有 Math.pow() JavaScript 的指数

use*_*799 0 javascript math loops exponentiation

我需要编写一个程序,该程序采用两个整数基数和指数,并在不使用 Math.Pow() 的情况下计算指数。我已经使用 Math.pow() 方法创建了代码,我不知道如何在没有它的情况下使其工作。我尝试过 base^exp 但它没有给我正确的答案。提前致谢!

/* 编写一个名为 intPow 的 JavaScript 函数,该函数从两个文本字段读取两个名为 base 和 exp 的数字。假设第二个数字始终是大于或等于 1 的整数。您的函数不应使用任何内置 Math 函数,例如 Math.pow。您的函数应该使用循环来计算 baseexp 的值,这意味着 base 的 exp 次幂。您的函数必须将 baseexp 的结果输出到 div。提示:编写函数来计算 1 乘以基本 exp 时间。*/

<!DOCTYPE HTML>
<html lang="en-us">

<head>
<meta charset="utf-8">
<title>Integer Power</title>
<script type="text/javascript">
    /* Write a JavaScript function named intPow that reads two numbers named base and exp from two text fields. Assume that the second number will always be an integer greater than or equal to 1. Your function should not use any of the built in Math functions such as Math.pow. Your function should use a loop to compute the value of baseexp meaning base raised to the power of exp. Your function must output the result of baseexp to a div. Hint: write your function to compute 1 multiplied by base exp times. */
    function intPow() {
        var base = parseFloat(document.getElementById("baseBox").value);
        var exp = parseFloat(document.getElementById("expBox").value);
        var output = "";
        var i = 0;
        for (i = 1; i <= exp; i++) {
            output = Math.pow(base, exp);
        }
        document.getElementById("outputDiv").innerHTML = output;
    }
</script>
</head>

<body>
<h1>Find the power of <i>Base</i> by entering an integer in the <i>base</i> box, and an integer in the <i>exponent</i> box.</h1> Base:
<input type="text" id="baseBox" size="15"> Exponents:
<input type="text" id="expBox" size="15">
<button type="button" onclick="intPow()">Compute Exponents</button>
<div id="outputDiv"></div>
</body>

</html>`
Run Code Online (Sandbox Code Playgroud)

mar*_*tte 5

对于将来查找此问题的任何人(例如我现在)来说,这是一个可靠的解决方案:

function computePower(num, exponent) {
      var result = 1;
      for (i = 0; i < exponent; i++) {
      result *= num;
      }
      return result;
  } 
Run Code Online (Sandbox Code Playgroud)

给定一个数字和一个指数,“computePower”返回给定的数字,并增加到给定的指数。

@用户5500799,

output = (1 * base ) * exp;
Run Code Online (Sandbox Code Playgroud)

不起作用,因为你没有将底数提高到指数,只是将其相乘。从 1 的乘法开始是很好的:在我的代码中,这确保了,例如,2 的 0 次方是 1(0 次方的所有内容都是 1,这是定义的)