我试图在VBA中检查给定的数字是否为Cuberoot 以下代码仅适用于2和3作为答案,之后不起作用 我试图找出代码中的错误。
Sub cuberoot()
Dim n As Long, p As Long, x As Long, y As Long
x = InputBox("x= ")
If Iscube(x) Then
MsgBox ("Is cube")
Else
MsgBox ("No cube")
End If
End Sub
Private Function Iscube(a As Long) As Boolean
b = a ^ (1 / 3)
If b = Int(b) Then
Iscube = True
Else
Iscube = False
End If
End Function
答案 0 :(得分:2)
因为你传递Long
我会假设你的数字不会超过大约2 * 10 ^ 9,所以这应该总是有效。这是一个轻微的变化,你截断double,然后比较两个最接近的整数,以确保你捕获任何舍入错误。
编辑:在VBA中,截断将始终为圆,因此只需检查第3个根值:
Public Function Iscube(a As Long) As Boolean
Dim b As Integer
b = CInt(a ^ (1# / 3#))
If (b ^ 3 = a) Then
Iscube = True
Else
Iscube = False
End If
End Function
如果您需要一个大于Long
的数字,则需要更改输入类型,而您可能需要考虑迭代方法,如二元搜索或Newton-Raphson求解器。
答案 1 :(得分:1)
Existing Code
Your code will work if you add a
dim b as long
If you debug your code you will see that feeding in 125 gives you
b = 5
Int(b) = 4
Updated Code
You can shorten your boolean test to this
Function Iscube(lngIn As Long) As Boolean
Iscube = (Val(lngIn ^ (1 / 3)) = Int(Val(lngIn ^ (1 / 3))))
End Function
Note that if you call it with a double, it will opearte on the long portion only (so it would see IsCube(64.01)
as IsCube(64)
)