samedi 29 août 2020

Random float in C# [duplicate]

I need to generate a random number in C# for a program I'm writing. Let's say I need to generate a number between -3 and 3. I know I can generate an integer with

System.Random random = new System.Random(); 
float rndNumber = random.Next(-3, 4);

However, this only gives whole numbers (ex. -2, 1, 2, 0). This doesn't generate any decimals. Although you can generate decimals like this

var rand = new Random();
var rndNumber = new decimal(rand.NextDouble());

This gives decimals (ex. 0.47, 0.93, 0.58). But how would I generate numbers that aren't just a whole number? For example 1.04, 1.98, or -0.73 but no going under or over -3 and 3?




Aucun commentaire:

Enregistrer un commentaire