【发布时间】: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