VBA 中的简单递归函数与 Excel 不返回预期结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9071559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple recursive function in VBA with Excel not returning expected result
提问by Yass T
I have a simple recursive function to write in VBA that does the following : It must count the number of times we must take the log of a parameter 'x' to find log(x) < 1
我有一个简单的递归函数可以在 VBA 中编写,它执行以下操作:它必须计算我们必须获取参数“x”的日志才能找到 log(x) < 1 的次数
Examples :
例子 :
- logcount(5) : log(5) = 0,6... so the function should return 1
- logcount(89) : log(89) = 1,9... and log(log(89)) = 0,28... so the function should return 2
- logcount(0,4) should return 1 etc...
- logcount(5) : log(5) = 0,6... 所以函数应该返回 1
- logcount(89) : log(89) = 1,9... and log(log(89)) = 0,28... 所以函数应该返回 2
- logcount(0,4) 应该返回 1 等等...
So I wrote it and it doesn't work as expected ! It always adds +1 to the result ! It looks like the last 'Else' block is always interpreted. Any help will be really appreciated
所以我写了它,但它没有按预期工作!它总是将 +1 添加到结果中!看起来总是解释最后一个“Else”块。任何帮助将不胜感激
Function logcount(x As Double) As Integer
If x <= 0 Then
MsgBox "You must enter a positive value"
Exit Function
ElseIf Log(x) < 1 Then
logcount = 1
Else
logcount = 1 + logcount(Log(x))
End If
End Function
回答by GSerg
Log
in VBAis the natural logarithm.
Log
在 VBA 中是自然对数。
Apparently you meant a base-10 logarithm:
显然你的意思是一个以 10 为底的对数:
Log10 = Log(X) / Log(10#)