使用递归函数进行双倍倒计时?
我正在尝试使用JavaScript编写递归,而无需使用全局变量,但我不确定该程序是否可以像Desire Output一样。
问题是“给出了一个非负整数n,在输出中创建一个双重倒计数模式”。 例子: 如果您运行了Doublecountdown(5),您还将获得以下输出:
5
4
3
2
1
4
3
2
1
0
我尝试了以下方式: 这样,下降到输出而不是确切的输出:
double_countdown(5);
function double_countdown(n){
if(n == 0){
console.log(n);
return
}
console.log(n);
double_countdown(n-1);
console.log(n);
}
通过这种方式,我将全球用于所需的输出,但不是标准方式。
let second_n = 0;
let double_count =0;
double_countdown(5);
function double_countdown(n){
if(n == 0 && double_count == 0){
double_count = 1;
double_countdown(second_n-1);
console.log(n);
}
if(n == 0){
return
}else{
second_n +=1;
}
console.log(n);
double_countdown(n-1);
}
I'm trying to write a recursion using JavaScript, without using global variables but i am not sure that the program can be possible like desire output.
Question is "Given a non-negative integer n, create a double countdown-pattern in the output."
Example:
If you ran doubleCountdown(5) you would also get the following output:
5
4
3
2
1
4
3
2
1
0
I have tried following ways:
In this way getting down to up output but not exact output:
double_countdown(5);
function double_countdown(n){
if(n == 0){
console.log(n);
return
}
console.log(n);
double_countdown(n-1);
console.log(n);
}
In this ways, i have used global for desired output but not standard way.
let second_n = 0;
let double_count =0;
double_countdown(5);
function double_countdown(n){
if(n == 0 && double_count == 0){
double_count = 1;
double_countdown(second_n-1);
console.log(n);
}
if(n == 0){
return
}else{
second_n +=1;
}
console.log(n);
double_countdown(n-1);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会将单个倒计时编写为递归函数,并让双倒计时函数只需调用它两次。这使得所有部件都很简单。
然后,您可以按照您想要的方式记录家庭作业的答案。也许类似于
for (let n of doubleCountdown (5)) {console .log (n)}
I would write the single countdown as a recursive function and have a double countdown function simply call it twice. This keeps all the parts simple.
You can then log the answer however you want for your homework. Perhaps something like
for (let n of doubleCountdown (5)) {console .log (n)}
通过提供和使用更多的参数来跟踪其递归状态的方式实现递归函数,而不仅仅是所需的第一个参数(这是当前的计数值)。
因此,将实现一个能够下计数周期
n
次的函数。double_countdown
分别CountDownTwice
函数可以从这种通用实现中派生。Implement the recursive function in a way that it keeps track of its recursion state by providing and working with more parameters than just the required first parameter (which is the current count down value).
Thus one would implement e.g. a function which is capable of running the count down cycle
N
times. And adouble_countdown
respectivelycountDownTwice
function could be derived from such a generic implementation.最后,经过多次尝试,我得到了答案:
Finally, after trying many times, I got the answer: