VBS脚本随机并切换

时间:2016-03-16 16:06:36

标签: random vbscript wsh

在下面的程序中,r被初始化为舍入的随机数,并提示用户猜测。如果用户猜对了,则有一个提示,否则会有另一个提示。代码看起来正确,但在运行时,选择Else案例是否用户得到了正确的数字。请帮助我多次阅读它以免疼。

Set WshShell = WScript.CreateObject("WScript.Shell")
'This script is designed to create a random number, and have a user guess the number
'If the user guesses the number incorrectly, negatively impact the users system
'if the user guess the number correctly, do nothing

dim InputValue
dim UserInput
'create a random number
dim r
randomize
r = int(rnd * 10)+1

'Allow the user to guess what number is correct
Input = inputbox ("Choose a number from one to ten, and choose wisely ;)", "Type a number.")
InputValue = Input
'Provide the user with feedback as to what his/her choice was and what the number actually was.
UserInput = "You typed " & InputValue & "." & " The number was " & r & "."
'echo the random generated number for test purposes
WScript.Echo r




Select Case InputValue
    Case r
        WScript.Echo "No action"
    Case Else
        WScript.Echo "Negative Action"
End Select

1 个答案:

答案 0 :(得分:3)

问题是InputValueString类型,因为InputBox函数和r返回的内容是Integer 1}},因此当您将InputValuer进行比较时,您需要将字符串与整数进行比较,即将苹果与橙子进行比较。

概念证明:

Dim x
x = "5"

Dim y
y = 5

Select Case x
    Case y
        MsgBox "Yes" 
    Case Else
        MsgBox "No" 'this is what happens.
End select

VBScript不是强类型语言,也就是说它根本不知道类型 - 嗯,它有点知道。它将每个变量视为一种称为"变体"然后,它本身可以与更具体的类型具有亲和力,但是以非常混乱和容易出错的方式。我说你应该read this来了解更多信息。

你可能会遇到很多麻烦,除非你总是确定你知道什么"类型"你正在与之合作。

尝试将其更改为:

InputValue = CInt(Input)

现在你正在转换"字符串"进入"整数" (变量实际上仍然是"变体"但它们与整数具有相同的基础亲和力)。但是,您需要小心,因为有人可能会输入能够转换为整数的值,例如hello,因此您会在此行中收到错误消息。在转换之前,您需要先进行一些错误检查。

相关问题