水仙花数vb编程怎么

时间:2025-01-27 03:23:51 网络游戏

在Visual Basic(VB)中,可以通过以下几种方法来编写查找水仙花数的程序:

方法一:使用循环和取余运算符

```vb

Private Sub Command1_Click()

Dim i As Integer

Dim s As Integer

Dim a As Integer, b As Integer, c As Integer

Print "100到999所有水仙花数(也叫梅花数):"

For i = 100 To 999

a = i \ 100 ' 取百位数

b = i \ 10 Mod 10 ' 取十位数

c = i Mod 10 ' 取个位数

s = a ^ 3 + b ^ 3 + c ^ 3 ' 水仙花数的判断依据

If s = i Then

Print i

End If

Next i

End Sub

```

方法二:使用嵌套循环

```vb

Private Sub Form_Click()

Dim i, j, k, n As Integer

n = 0

For i = 100 To 999

For j = 0 To 9

For k = 0 To 9

If i = j * 100 + k * 10 + k Then

n = n + 1

Print i

End If

Next k

Next j

Next i

MsgBox "三位数中水仙花数个数为 " & n

End Sub

```

方法三:使用数组和条件判断

```vb

Private Sub Form1_Click()

Dim a() As Integer

Dim n As Integer

n = InputBox("请输入一个n位正整数" & Chr(10) & "n大于等于3", "水仙花数", 153)

Dim i As Integer

m = Len(n)

For i = 1 To 9

For j = 0 To 9

For k = 0 To 9

If a(i) * 100 + a(j) * 10 + a(k) = a(i) ^ 3 + a(j) ^ 3 + a(k) ^ 3 Then

n = n + 1

Print a(i) * 100 + a(j) * 10 + a(k)

End If

Next k

Next j

Next i

Print Chr(13) & Chr(13) & "三位数中水仙花数个数为 " & n

End Sub

```

方法四:使用递归和循环

```vb

Private Sub Command1_Click()

Dim i As Integer

Dim s As Integer

Dim a As Integer, b As Integer, c As Integer

Print "100到999所有水仙花数(也叫梅花数):"

For i = 100 To 999

a = i \ 100 ' 取百位数

b = i \ 10 Mod 10 ' 取十位数

c = i Mod 10 ' 取个位数

s = a ^ 3 + b ^ 3 + c ^ 3 ' 水仙花数的判断依据

If s = i Then

Print i

End If

Next i

End Sub

```

方法五:使用列表和循环

```vb

Private Sub Command1_Click()

Dim i As Integer

Dim result As New List(Of Integer)()

For i = 100 To 999

Dim sum As Integer = 0

Dim num As Integer = i

While num > 0

Dim digit As Integer = num Mod 10

sum += digit ^ 3

num \= 10

End While

If sum = i Then

result.Add(i)

End If

Next i

For Each num In result

Print num

Next num

End Sub

```

这些方法都可以用来查找水仙花数,你可以根据自己的需求和编程习惯选择合适的方法。