NewMan-VB
NewMan-VB

Reputation: 21

Can sb help me to correct my vb code?

Dim age As Integer = 1

Do While 1980 + age <> age * age
    lblResult.Text = "The solution is " & age & " years old."
    age = age + 1
Loop

When I run this program, it will give 44 not 45. Is there anything with it?

Upvotes: 0

Views: 73

Answers (1)

Michael Liu
Michael Liu

Reputation: 55389

The problem is that the code updates lblResult.Text before it increments age, so when age is incremented from 44 to 45, the loop exits without updating the label to show the final value of age.

To fix the code, update lblResult.Text after incrementing age. Although you could do so inside the loop ...

Do While 1980 + age <> age * age
    age = age + 1
    lblResult.Text = "The solution is " & age & " years old."
Loop

... it suffices to update the label just once, after the loop finishes:

Do While 1980 + age <> age * age
    age = age + 1
Loop

lblResult.Text = "The solution is " & age & " years old."

Upvotes: 1

Related Questions