Visual Basic中的常见因素

问题描述 投票:0回答:1

我试图通过找到公因子来对方程进行因式分解,例如:

4x+2y = 2(2x+y)

所以基本上

If n1 <> n2 Then

End If 

是问题所在,因为我不知道要输入什么。

我尝试这样做:

if n1/n2 = whole number 
n3 = n1/n2
MsgBox(n3 & "(" & l1 & "+" & l2 & ")")

但我无法弄清楚整个数字代码,当我确实让它工作时我意识到它也不会划分数字,所以如果问题是:

4x+2y

答案是:

2(2x+y)

但是电脑给了我:

2(x+y)

到目前为止,我有:

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim n1 As Integer
        Dim n2 As Integer
        Dim l1 As String
        Dim l2 As String

        n1 = InputBox("what is the first number ")
        l1 = InputBox("what is the first letter ")
        n2 = InputBox("what is the second number ")
        l2 = InputBox("what is the second letter ")

        If n1 = n2 Then
            MsgBox(n1 & "(" & l1 & "+" & l2 & ")")
        End If
        If n1 <> n2 Then

        End If
    End Sub
End Class

我想让它分解,所以它是正确的。

如果问题是:

4x+12y

我希望它是:

4(x+3y) 

而不是我得到的是:

4(x+y)
vb.net math algebra
1个回答
1
投票

您正在寻找的代码是:

If n1 <> n2 Then        
    If n1 Mod n2 = 0 Then
        Dim n3 = n1 / n2
        MsgBox(n3 & "(" & (n1 / n3) & l1 & "+" & (n2 / n3) & l2 & ")")
    End If
End If

模运算符Mod给出整数除法的余数。因此,如果n1 Mod n2为零,那么n2n1的除数。然后,在你的最终结果中,你需要取消n3

但是,这并不是您想要做的。因为这也不会改变输入6x + 4y的任何内容。你想要做的是分解出最大的公约数。这可以用Euclidean algorithm计算。这是完整的代码:

Private Function GreatestCommonDivisor(a As Integer, b As Integer) As Integer
    If a = 0 Then Return b
    Return GreatestCommonDivisor(b Mod a, a)
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim n1 As Integer
    Dim n2 As Integer
    Dim l1 As String
    Dim l2 As String

    n1 = InputBox("what is the first number ")
    l1 = InputBox("what is the first letter ")
    n2 = InputBox("what is the second number ")
    l2 = InputBox("what is the second letter ")

    Dim n3 = GreatestCommonDivisor(n1, n2)
    MsgBox(n3 & "(" & (n1 / n3) & l1 & "+" & (n2 / n3) & l2 & ")")
End Sub

这将打印2(2x + 1y)4x + 2y2(3x + 2y)6x + 4y

© www.soinside.com 2019 - 2024. All rights reserved.