具有随机整数的数组

时间:2016-10-25 05:54:13

标签: vb.net

我想编写一个程序,首先生成三个随机整数,然后打印出它们的正方形和立方体。

enter image description here

我已经有了计算和输出,但我不知道如何生成随机数。

Dim NumOfIntegers() As Integer = {1, 2, 3, 4, 8}
Dim x, y As Integer
For Each num As Integer In NumOfIntegers
    x = num ^ 2
    y = num ^ 3
    MessageBox.Show("Square Of " & num & " = " & x & vbCrLf & "Cube Of " & num & " = " & y)
Next

1 个答案:

答案 0 :(得分:0)

此代码使用1到100之间的3个不同随机数填充整数列表

Dim NumOfIntegers As New List(Of Integer)

While NumOfIntegers.Count < 3
    Dim i As Integer = CInt(Math.Ceiling(Rnd() * 100)) + 1
    If Not NumOfIntegers.Contains(i) Then NumOfIntegers.Add(i)
End While

NumOfIntegers.Sort()

Dim x, y As Integer    
For Each num As Integer In NumOfIntegers
    x = num ^ 2
    y = num ^ 3
    MessageBox.Show("Square Of " & num & " = " & x & vbCrLf & "Cube Of " & num & " = " & y)
Next

代码,如果您只想使用for循环:

(未经测试的代码和3个整数内可能是重复的)

Dim NumOfIntegers() As New Integer = {(CInt(Math.Ceiling(Rnd() * 100)) + 1), (CInt(Math.Ceiling(Rnd() * 100)) + 1), (CInt(Math.Ceiling(Rnd() * 100)) + 1)}

Dim x, y As Integer    
For Each num As Integer In NumOfIntegers
    x = num ^ 2
    y = num ^ 3
    MessageBox.Show("Square Of " & num & " = " & x & vbCrLf & "Cube Of " & num & " = " & y)
Next