检查数字是否具有整数立方根

时间:2015-04-22 21:04:57

标签: vba

我试图在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

2 个答案:

答案 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))