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!
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;
}
+ 9
Sure. You can use Random class, take a look :
https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netframework-4.7.2
+ 9
https://www.c-sharpcorner.com/article/generating-random-number-and-string-in-C-Sharp/
+ 1
Thanks everyone. The links ans explanations were all very helpful
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?