简体   繁体   中英

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.

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)"

The error message tells you precisely the problem. Random is a class. Next is a non-static method. 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). 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. Simply use NextDouble() , which gives a value greater than or equal to 0 and less than 1.0.

double d = random.NextDouble();

Random is a class. Random.Next() is a non-static method.

Therefore you need to instantiate an instance of the Random class. (Note: as Spender pointed out, don't make this local to a loop...)

Random rnd = new Random();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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