如何生成随机数 [英] How to generate random numbers

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

问题描述

我是 vb 新手,我有 3 个文本框,当用户单击表单中的特定按钮时,我想将其设置为随机值,因此:
这是代码:

i'm new to vb and i have 3 textboxs that i want to set it to a random value when the user click a specific button in in the form so :
here's the code :

Private Sub cmdjouer_Click(Index As Integer)
  txt1 = Math.Randomize(9)
 txt2 = Math.Randomize(9)
 txt3 = Math.Randomize(9)
End Sub

我收到以下错误期望的函数或变量

我确定问题出在 Randomize 函数上.

i'm sure that the problom is with the Randomize function.

任何想法将不胜感激

推荐答案

您将 VB.NET 与 VB6 混淆了.它们彼此截然不同.以后,当您在线查找示例、文档和帮助时,请务必指定 VB6,以确保您使用的是正确的语言.它们本质上是两种完全不同的语言.

You are confusing VB.NET with VB6. They are drastically different from each other. In the future, when you look for examples, documentation, and help online, be sure to specify VB6 to ensure that you are dealing with the correct language. They are essentially two completely different languages.

在 VB6 中,您需要首先使用 Randomize 函数为随机数生成器设置种子.然后,要生成随机数,必须使用 Rnd 函数,例如:

In VB6, you need to initially seed the random number generator using the Randomize function. Then, to generate a random number, you must use the Rnd function, for instance:

Private Sub cmdjouer_Click(Index As Integer)
    Randomize()
    txt1.Text = Int((Rnd * 9) + 1)
    txt2.Text = Int((Rnd * 9) + 1)
    txt3.Text = Int((Rnd * 9) + 1)
End Sub

VB.NET

Math.Randomize 是智能个人对象技术 (SPOT) 命名空间中的一种方法.我怀疑这就是你真正要找的.您可能只想使用 System.Random 类,如下所示:

VB.NET

Math.Randomize is a method in the Smart Personal Objects Technology (SPOT) namespace. I doubt that is what you are actually looking for. You probably just want to use the System.Random class, like this:

Private Sub cmdjouer_Click(sender As Object, e As EventArgs) Handles cmdjouer.Click
    Dim r As New Random()
    txt1.Text = r.Next(9).ToString()
    txt2.Text = r.Next(9).ToString()
    txt3.Text = r.Next(9).ToString()
End Sub

正如其他人指出的那样,您不想将文本框引用变量设置为数字(例如 txt1 = ...).您需要设置文本框的 Text 属性.

As others have pointed out, you don't want to set your text box reference variable to the number (e.g. txt1 = ...). You need to set the Text property of the text box.

此外,正如在下面的评论中指出的那样,我在按钮的 Click 事件中调用了 Randomize 或创建了 New Random 对象.我这样做是为了简化示例,但实际上,这将是不好的做法.在任何一种情况下,理想情况下,随机数生成器的播种应该只发生一次,通常是在应用程序启动时.通过每次重新播种生成器,可以使结果的随机性降低.

Also, as was pointed out in the comments below, I called Randomize or created the New Random object inside the button's Click event. I did so to simplify the example, but in actuality, that would be bad practice. In either case, the seeding of the random number generator should, ideally, only happen once, typically when the application starts. By re-seeding the generator each time, it can cause the results to be less random.

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

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