0

How to generate random value for a variable in C#?

Is there a command that exists in the C# language that would allow my code to assign a random positive value to an int or double variable and maybe a way to set the range of possibilities? Something like: int x = (randomValue); Or a method I can create? int x = randomValue(); Thanks!

23rd Jan 2019, 9:09 PM
JPressley
JPressley - avatar
5 ответов
+ 2
JPressley In C# the Random class is included in the standard System namespace, you dont need any additional library to use it. It is pretty simple: using System; static void Main(string[] args) { //Initialize a new object of random class Random rand = new Random(); // Get a random integer between 0 and 100 and store it in a variable int x = rand.Next(101); //Print a random number between 0 and 100 Console.WriteLine(x); //For floating point you need to use NextDouble() instead and it will generate a random double number between 0 and 1 x = rand.NextDouble(); //if you want a floating point in a greater range you need to multiplicate it, for example to get a random float between 0 and 12 you do x = rand.NextDouble() * 12; }
24th Jan 2019, 12:04 AM
Sekiro
Sekiro - avatar
23rd Jan 2019, 9:15 PM
dρlυѕρlυѕ
dρlυѕρlυѕ - avatar
+ 9
https://www.c-sharpcorner.com/article/generating-random-number-and-string-in-C-Sharp/
23rd Jan 2019, 9:17 PM
Mert Yazıcı
Mert Yazıcı - avatar
+ 1
Thanks everyone. The links ans explanations were all very helpful
24th Jan 2019, 12:11 AM
JPressley
JPressley - avatar
0
Right I thought that! But it doesn't show up as a suggestion or compile in my code. Using Visual Studios. The example links only show the System library. Do i need to use additional libraries?
23rd Jan 2019, 10:32 PM
JPressley
JPressley - avatar