VB.NET中的随机函数 [英] Random Function in VB.NET

查看:85
本文介绍了VB.NET中的随机函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何选择0.1到5.0之间的随机值?
我该怎么办?

这是生成随机整数的代码...但是当我尝试使用double值时,它不起作用..仍然给出一个整数值..
帮助我生成随机的双重谷歌...



昏暗的objRandom作为新System.Random(_
CType(System.DateTime.Now.Ticks Mod System.Int32.MaxValue,Integer))

公共函数GetRandomNumber(_
可选ByVal Low As Integer = 1,_
可选ByVal High As Integer = 100)As Integer
''返回一个随机数,
''在可选的低和高参数之间
返回objRandom.Next(Low,High + 1)
结束功能


这是我在代码中如何使用此功能的方法:


将IntDiceRoll设置为Integer
intDiceRoll = GetRandomNumber(1,6)
MessageBox.Show(您滚动了一个&intDiceRoll.ToString)

how to pick a random value from 0.1 to 5.0 ??
what should i do for that?

this is the code to generate random integer number ...but when i try it for double value its not working .. still give a interger value ..
help me to generate random double vale...



Dim objRandom As New System.Random( _
CType(System.DateTime.Now.Ticks Mod System.Int32.MaxValue, Integer))

Public Function GetRandomNumber( _
Optional ByVal Low As Integer = 1, _
Optional ByVal High As Integer = 100) As Integer
'' Returns a random number,
'' between the optional Low and High parameters
Return objRandom.Next(Low, High + 1)
End Function


And here’s how i use this function in code:


Dim intDiceRoll As Integer
intDiceRoll = GetRandomNumber(1, 6)
MessageBox.Show("You rolled a " & intDiceRoll.ToString)

推荐答案

使用System.Random.NextDouble返回范围为0d .. 1d的double值,然后线性将结果转换为1d .. 5d范围.请参阅:
http://msdn.microsoft.com/en-us/library/system.random. nextdouble.aspx [ ^ ].

我什至需要解释如何?初中的初等代数永远都不会忘记. :-)

—SA
Return the double value in the range 0d .. 1d using System.Random.NextDouble and then linear-transform the result into the range 1d .. 5d. Please see:
http://msdn.microsoft.com/en-us/library/system.random.nextdouble.aspx[^].

Do I even need to explain how? Elementary algebra for middle school is never bad to remember. :-)

—SA


这篇关于VB.NET中的随机函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆