0

我想为我正在创建的游戏生成一个介于 1 和 20 之间的随机数,由于某种原因,此代码停止工作并给我一个类型不匹配错误,我在游戏中尝试了其他生成器,但我得到了同样的错误。

Public Counter1 As Integer ' Counters for each reel
Public ArrayImgMid1 As Integer ' Store number to iterate over image arrays
Public ReelPic1 As Variant ' Array of images for each reel
Public Reel1Spin As Long ' Spins for each reel
Public ImgBeth, ImgWallow, ImgDan, ImgChris, ImgCatBug As StdPicture ' Images for reels

Private Sub CmdSpin_Click()

'Enable all timers to imitate spinning
TimerReel1.Enabled = True
TimerReel1.Interval = 100

' Disable spin button
CmdSpin.Enabled = False

' Set all counters to 0
Counter1 = 0

' Generate random number for the first reel to spin
Reel1Num = (CLng(Rnd * 20) + 1) ' This is highlighted when I press debug
4

1 回答 1

4

像这样写:

Dim Reel1Num As Long

Reel1Num = (CLng(Rnd * 20) + 1)

不要Integer在 VB6 中使用 - 它表示 16 位有符号整数,其性能略低于Long真正的 32 位有符号整数。这样您也不会遇到 16 位数据类型的限制。

您的代码不起作用的原因是该Int()函数不会将值的数据类型转换为类型Integer- 它会将指定的值四舍五入为整数值但保留其数据类型。

要将值转换为特定数据类型,请使用CInt()CLng()等函数。但正如我所说,Integer除非你特别需要,否则避免使用 -Long在大多数情况下会更好。

编辑:

发布代码后,我看不到Reel1Num变量的定义 - 它在哪里定义?是Reel1Spin吗?如果是这种情况,请确保启用该Require variable declaration选项Tools->Options- 默认情况下它是关闭的。如果你没有穿上它,这是一个非常简单的方法来射击自己的脚。

与您的错误无关,但您的大多数图像对象定义不正确 - 在 VB6 中,必须为每个变量指定变量的类型,而不是每行一次。所以在这一行:

Public ImgBeth, ImgWallow, ImgDan, ImgChris, ImgCatBug As StdPicture

您只真正创建了 1 个StdPicture对象,所有其他对象都将是变体。正确的做法是:

Public ImgBeth As StdPicture, ImgWallow As StdPicture, ImgDan As StdPicture, _
    ImgChris As StdPicture, ImgCatBug As StdPicture

除了这些,我看不出你的代码有什么问题——我的电脑上没有安装 VB6。请记住,VB6 有一种处理类型不匹配的时髦方法,在某些情况下,突出显示的行可能不是导致实际错误的行。这曾经让我发疯。

于 2013-05-10T20:11:14.537 回答