【问题标题】:Exponents without Math.pow() JavaScript没有 Math.pow() JavaScript 的指数
【发布时间】:2016-02-14 16:10:11
【问题描述】:

我需要编写一个程序,它需要两个整数基数和指数,并在不使用 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>`

【问题讨论】:

  • 为什么math.Pow()不适合?
  • 提示:a ^ b = a * a * a ... (b times).
  • @simoco 因为这是学习循环的家庭作业。
  • 但是这里不是给别人做作业的地方
  • 我不要求任何人做我的硬件我要求指导。我已经完成了大部分代码。我只是不明白如何在没有 math.pow() 的情况下计算指数

标签: javascript loops math exponentiation


【解决方案1】:

对于任何在未来寻找这个的人,比如我刚才,这是一个可靠的解决方案:

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

给定一个数字和一个指数,“computePower”返回给定的数字,提升到给定的指数。

@user5500799,

output = (1 * base ) * exp;

行不通,因为您没有将底数提高到指数,只是将其相乘。不过,从与 1 的乘法开始很好:在我的代码中,这可以确保,例如,2 的 0 次方是 1(所有的 0 次方都是 1,这是已定义的)

【讨论】:

  • 不够扎实,试试computePower(2, 0.5)会得到错误的结果。
【解决方案2】:

在 ES2016 中,您可以使用 exponentiation operator

2 ** 8 // 256

【讨论】:

    【解决方案3】:

    我能够通过将输出更改为:

    输出 = (1 * 基数) * exp;

    【讨论】:

      猜你喜欢
      • 2011-10-18
      • 2015-09-24
      • 2016-12-04
      • 2013-12-06
      • 2014-01-25
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多