在循环中显示特定结果

时间:2015-06-02 20:37:18

标签: vb.net visual-studio-2010 vba loops

我正在尝试创建一个能够使用RSA加密系统进行编码的程序。为此,我创建了能够使用Euclidean Algorithm计算的代码。这是代码:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    number1 = TextBox1.Text
    number2 = TextBox2.Text
    Do While answer <> 0
        answer = number1 Mod number2
        number2 = number1 And answer = number2
    Loop
    MessageBox.Show(answer)
End Sub

所以,这没什么难的,对吧​​?问题是它总是会显示0作为答案,这是有道理的。但是我希望在最后一个之前得到循环的答案。

这是一个[例子]

enter image description here

如果你不明白我想说的话。

我希望有人能够帮助我:)。

2 个答案:

答案 0 :(得分:1)

为什么不在设置之前声明一个变量来保持答案并检查它是否为0?

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As                                                            System.EventArgs) Handles Button2.Click
Dim number1
Dim number2
Dim answer
Dim whatIWant
    answer = -1
    number1 = TextBox1.Text
    number2 = TextBox2.Text
Do While answer <> 0    
    answer = number1 Mod number2
    number1 = number2
    number2 = answer        
    If answer <> 0 Then
        whatIWant = answer
    End If
Loop
MessageBox.Show (CStr(whatIWant))

End Sub

这是一个简单的测试,您可以在Excel中完成,Messagebox在完成时显示99。

Sub TestIt()
Dim number1
Dim number2
Dim answer
Dim whatIWant
    answer = -1
    number1 = 148104 'TextBox1.Text
    number2 = 47223 'TextBox2.Text
Do While answer <> 0
    answer = number1 Mod number2
    number1 = number2
    number2 = answer

    If answer <> 0 Then
        whatIWant = answer
    End If
Loop
MsgBox (CStr(whatIWant))

End Sub

答案 1 :(得分:1)

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As                                                            System.EventArgs) Handles Button2.Click
        dim prevAnswer as integer
        number1 = TextBox1.Text
        number2 = TextBox2.Text
        Do While answer <> 0
            prevAnswer = answer
            answer = number1 Mod number2
            number2 = number1 And answer = number2
        Loop
    MessageBox.Show(prevAnswer)
    End Sub