简体   繁体   English

C#中的随机数问题

[英]Trouble with Random Numbers in C#

I'm sure this question is asked a lot but I cannot find an answer anywhere that helps me. 我敢肯定这个问题被问了很多,但是我找不到任何可以帮助我的答案。 I'm trying to create a random double between 0 and 1, and I keep getting errors. 我正在尝试在0和1之间创建一个随机双精度数,并且不断出错。

map[x,y].setBit((int) Math.Round(((((double)Random.Next(100))/100) * 1.3), 2);

the error I get says "An object reference is required for the non-static, method, or property "System.Random.Next(int)" 我得到的错误是:“非静态,方法或属性“ System.Random.Next(int)需要对象引用”

The error message tells you precisely the problem. 错误消息将告诉您确切的问题。 Random is a class. Random是一类。 Next is a non-static method. Next是一种非静态方法。 You need an instance, or object reference, of the class in order to use that method. 您需要类的实例或对象引用才能使用该方法。

var random = new Random();
// use random.Next(upperLimit);

You should note that if you are using random in a tight loop, you would want to create the instance outside the loop and reuse it, or at an otherwise higher level (such as a member field of a class). 您应该注意,如果在紧密循环中使用random ,则需要在循环外部创建实例并重用它,或者在更高级别(例如,类的成员字段)重用它。 The way the class is seeded, successive instances will generate the same "random" sequences of values. 类的种子播种方式,连续的实例将生成相同的“随机”值序列。 This is a common pit that people have fallen into . 这是人们陷入的普遍困境


You should also be aware that based upon your usage where you are getting an integer from 0 to 99, casting to double, and dividing by 100... there's a more straightforward approach. 您还应该意识到,根据您的用法,您将获得一个从0到99的整数,转换为两倍,然后除以100 ...是一种更简单的方法。 Simply use NextDouble() , which gives a value greater than or equal to 0 and less than 1.0. 只需使用NextDouble() ,它给出的值大于或等于0且小于1.0。

double d = random.NextDouble();

Random is a class. 随机是一类。 Random.Next() is a non-static method. Random.Next()是一种非静态方法。

Therefore you need to instantiate an instance of the Random class. 因此,您需要实例化Random类的实例。 (Note: as Spender pointed out, don't make this local to a loop...) (注意:正如Spender指出的那样,请不要将此局部设置为循环...)

Random rnd = new Random();

map[x,y].setBit((int) Math.Round(((((double)rnd.Next(100))/100) * 1.3), 2); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM