vb.net 2 个变量/值之间的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20173213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random Number between 2 variables/values
提问by Brian Smith
I am working on a project for a intro VB class. I need to create a random number between 2 values the user enters. I have an upper limit textbox/variable and a lower limit textbox/variable. I have tried everything I could find and it produces weird results. I can't figure out how to get the random numbers generated between 2 values. For example if the user enters 100 for the lower limit and 500 for the upper limit the random should be in the range of 100-500.
我正在开发一个介绍 VB 类的项目。我需要在用户输入的 2 个值之间创建一个随机数。我有一个上限文本框/变量和一个下限文本框/变量。我已经尝试了所有我能找到的方法,但它产生了奇怪的结果。我不知道如何在 2 个值之间生成随机数。例如,如果用户为下限输入 100,为上限输入 500,则随机数应在 100-500 的范围内。
Please let me know what I am doing wrong??
请让我知道我做错了什么??
'Grabs the txbox input and assigns to vars
intLowNumber = CInt(mskLowerRange.Text)
intUpperNumber = CInt(mskUpperRange.Text)
intRandomNumber = rand.Next(intUpperNumber) - intLowNumber
'Output to listbox and textbox
lstOutput.Items.Add(intRandomNumber)
txtNumber.Text = CStr(intRandomNumber)
回答by Thorkil Holm-Jacobsen
Your code is wrong, specifically
你的代码是错误的,特别是
intRandomNumber = rand.Next(intUpperNumber) - intLowNumber
Say intUpperNumberis 200 and intLowNumberis 100, the above gives somewhere between -100 (0 - 100) and 99 (199 - 100).
说intUpperNumber是 200 和intLowNumber100,上面给出了介于 -100 (0 - 100) 和 99 (199 - 100) 之间的某处。
You can give Random.Next two parameters for a random number in a range.The first parameter is the minimum value and the second parameter is the maximum value of the random number.
您可以为范围内的随机数提供 Random.Next 两个参数。第一个参数是最小值,第二个参数是随机数的最大值。
Note that the upper bound (the maximum value) is exclusive, so if you want to include the highest value you need to add 1. Use it like this:
请注意,上限(最大值)是独占的,因此如果要包含最大值,则需要加 1。像这样使用它:
'Grabs the txbox input and assigns to vars
intLowNumber = CInt(mskLowerRange.Text)
intUpperNumber = CInt(mskUpperRange.Text)
intRandomNumber = rand.Next(intLowNumber, intUpperNumber+1)
'Output to listbox and textbox
lstOutput.Items.Add(intRandomNumber)
txtNumber.Text = CStr(intRandomNumber)

