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

Apu*_*va 5 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

stu*_*aro 2

由于您传递的是 aLong我假设您不会有一个大于大约 2*10^9 的数字,所以这应该始终有效。这是一个细微的变化,您截断双精度值,然后与两个最接近的整数进行比较,以确保捕获任何舍入错误。

编辑:在 VBA 中,截断总是四舍五入,因此只需要检查第三个根值:

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
Run Code Online (Sandbox Code Playgroud)

如果您需要一个大于 a 的数字,Long则需要更改输入类型,并且您可能需要考虑使用迭代方法,例如二分搜索或牛顿拉夫森求解器。