很抱歉问了一个非常基本的问题。
刚刚开始。使用流程算法编写代码来计算指数数。
执行此操作的代码是:
function exponential(base, power) {
var answer;
answer = 1;
var i;
for (i = 1 ; i <= power ; i+= 1) {
answer = answer * base;
}
return answer;
f
然后循环至功率数。我只是明白流程图中的内容,但我不明白它的代码。 for 语句的每个部分的含义是什么? i = 1 的幂,我只需要帮助理解它是如何写的? 1+= 1 位是什么?
谢谢。
指数函数将采用 2 个参数:底数和幂。 您可以创建此函数并在需要时调用(触发)它,就像指数(2,4)一样。 for (i = 1; 1 <= power; i+=1) is somewhat of an ugly for loop. for loops traditionaly take three parameters. The first parameter in this case i =1 is the assignment parameter, the next one 1 <= power is the valadation parameter. So if we call the function like so...exponential(2,4) is i less than 4? The next parameter is an increment/decrement parameter. but this doesnt get executed until the code inside the for loop gets executed. Once the code inside the for loop is executed then this variable i adds 1 to itself so it is now 2. This is usefull because once i is no longer less than or equal to power it will exit the for loop. So in the case of exponential(2,4) once the code inside this for loop is ran 5 times it will exit the for loop because 6 > 5.
因此,如果我们查看变量答案,我们可以看到,在调用此 for 循环之前,答案等于 1。在此 for 循环的第一次迭代之后,答案 = 答案乘以基数。在指数(2,4) 的情况下,答案等于 1 乘以 2,现在答案 =2。但是我们只循环了 foo 循环一次,就像我说的 for 循环就像(赋值,验证器,“foo 循环内的代码”。然后返回到递增/递减)。因此,由于我们在指数(2,4)的情况下循环这个 for 循环 5 次,它看起来像这样。
指数(2,4)
answer = 1 * 2
now answer = 2
answer = 2 * 2
now answer = 4
answer = 4 * 2
now answer = 8
answer = 8 * 2
now answer = 16
答案 = 16 * 2 现在答案=32
所以如果我们可以说... var int ans =exponential(2,4) 那么 ans 将等于 32,因此返回答案;在代码的最后一行。