【问题标题】:Vb6 type mismatch with random number generatorVB6 类型与随机数生成器不匹配
【发布时间】:2013-05-13 01:54:01
【问题描述】:

我想为我正在创建的游戏生成一个介于 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

【问题讨论】:

    标签: vb6 type-mismatch


    【解决方案1】:

    这样写:

    Dim Reel1Num As Long
    
    Reel1Num = (CLng(Rnd * 20) + 1)
    

    不要在 VB6 中使用 Integer - 它表示一个 16 位有符号整数,它的性能略低于 Long,后者实际上是一个 32 位有符号整数。这样您也不会遇到 16 位数据类型的限制。

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

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

    编辑:

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

    与您的错误无关,但您的大多数图像对象定义不正确 - 在 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 有一种处理类型不匹配的时髦方法,在某些情况下,突出显示的行可能不是导致实际错误的行。这曾经让我发疯。

    【讨论】:

    • 感谢您的回答,但它仍然无法正常工作,一定与我的其余代码有关。虽然想不通
    • @Lilvlskid 为什么不发布更多代码?我们或许可以为您提供帮助。
    • @xxbbcc 感谢您的知情回复以及有用的提示以供将来参考,我已经开始了另一个版本的游戏,并且由于某种原因随机功能有效。如果我有声望,我会 +1。
    猜你喜欢
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多