VBscript 的递归问题

编程入门 行业动态 更新时间:2024-10-23 11:22:33
本文介绍了VBscript 的递归问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试在 vbscript 中实现一些递归.

I am trying to implement some recursion in vbscript.

Function largest_prime_factor (ByVal num) For i = 2 to num/2 If num mod i = 0 Then 'this number is not prime largest_prime_factor (num / i) End If Next largest_prime_factor = num ''if at this point, we have reached the largest prime End Function

如您所见,它是一个脚本,基本上旨在为我提供一个数字的最大质因数.然而,当我运行打印时,这个脚本仍然向我吐出推算的数字.调试后,我发现脚本确实会在 for 循环中输入条件,但是它不会递归(即:它将继续通过 for 循环运行,然后在该点之后结束)

As you can see, it is a script that is basically designed to give me the largest prime factor of a number. However, this script still spits back the imputed number at me when I run a print. After debugging, I have found that the script will indeed enter the conditional inside the for loop, but then it will NOT recurse (ie: it will keep running through the for loop and then just end after that point)

我对 VBscript 中的递归有什么误解?我也尝试了一些

What did I miss about recursion in VBscript? I also tried something to the effect of

largest_prime_factor = largest_prime_factor (num / i)

在条件中,这也不起作用.

Inside the conditional and this didn't work either.

推荐答案

在上面发布的代码中,您犯了两个小错误

In code posted above, you have made two minor mistakes

  • 您已经创建了返回数字的函数,在递归调用它时,您应该在变量num"中获取该数字以供进一步处理.
  • 您犯的第二个错误是在获得所需输出后没有退出循环.这会导致进一步循环,直到 i = num &在所有情况下,您的答案都是 1.
  • 工作代码---

    Function largest_prime_factor (ByVal num) For i = 2 to num/2 If num mod i = 0 Then 'this number is not prime num= largest_prime_factor (num / i) Exit For End If Next largest_prime_factor = num ''if at this point, we have reached the largest prime End Function

    更多推荐

    VBscript 的递归问题

    本文发布于:2023-11-30 20:34:12,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1651399.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:递归   VBscript

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!