输出不正确,以验证数字是否是完美的多维数据集Visual Basic

时间:2014-04-09 20:03:03

标签: vb.net

我有这个代码,显示两个数字之间的完美立方体的数量和它们之间的最小立方体。不成功的是,完美立方体的数量是不正确的。我的错误是什么?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim n As Integer
        Dim i As Integer

        Dim menor As Single
        Dim mayor As Single

        n = 0
        Dim primer As Integer
        Dim ver As Double


        menor = Val(menortxt.Text)
        mayor = Val(mayortxt.Text)
        For i = menor + 1 To (mayor - 1)
            ver = i ^ (1 / 3)
            If Int(ver) = ver Then
                n = n + 1
                If (n = 1) Then
                    primer = i
                End If

            End If
        Next
        rstxt.Text = "The first perfect cube is " & primer & vbNewLine & "The number of perfect cubes is " & n

1 个答案:

答案 0 :(得分:2)

问题是立方根计算i ^ (1 / 3)使用浮点运算,因此结果并不总是精确的,即在某些情况下会出现小错误。

另见How can I get the cube root in F#的答案。

一种选择是使用相同的算法,但使用BCL' BigRational类型的理由。

另一个可能更简单的解决方案是计算所有完美的立方体,直到上限值,然后简单地计算你在指定范围内找到的那个,即

    menor = CInt(menortxt.Text)
    mayor = CInt(mayortxt.Text)
    i = 1
    While (i * i * i) < mayor
        If (i * i * i) > menor Then
            If n = 0 Then
                primer = i
            End If
            n = n + 1
        End If
        i = i + 1
    End While
    Dim text =
        "The first perfect cube is " & primer & vbNewLine &
        "The number of perfect cubes is " & n