在 C# 中生成一个随机浮点数

使用 C# 中的 `Random.NextDouble()` 函数在 `0` 和 `1` 之间生成随机浮点数

``````using System;

namespace random_float {
class Program {
static void Main(string[] args) {
Random rand = new Random();
for (int i = 0; i < 10; i++) {
float randomFloat = (float)rand.NextDouble();
Console.WriteLine("Random Float = {0}", randomFloat);
}
}
}
}
``````

``````Random Float = 0.3914659
Random Float = 0.8927528
Random Float = 0.6579643
Random Float = 0.4404075
Random Float = 0.3213561
Random Float = 0.3399849
Random Float = 0.04562188
Random Float = 0.1881405
Random Float = 0.7638124
Random Float = 0.1645804
``````

使用 C# 中的 `Random.NextDouble()` 函数生成不带范围的随机浮点数

``````using System;

namespace random_float {
class Program {
static void Main(string[] args) {
Random rand = new Random();
double range = (double)float.MaxValue - (double)float.MinValue;
for (int i = 0; i < 10; i++) {
double sample = rand.NextDouble();
double scaled = (sample * range) + float.MinValue;
float f = (float)scaled;
Console.WriteLine(f);
}
}
}
}
``````

``````1.500952E+38
-1.930891E+38
2.951987E+38
-1.205054E+38
-6.225039E+37
3.843309E+36
-1.241292E+38
1.360907E+38
1.769061E+38
-1.577001E+38
``````

使用 C# 中的 `Random.NextDouble()` 函数在特定范围内生成随机浮点数

``````using System;

namespace random_float {
class Program {
static void Main(string[] args) {
Random rand = new Random();
double min = 1;
double max = 10;
double range = max - min;
for (int i = 0; i < 10; i++) {
double sample = rand.NextDouble();
double scaled = (sample * range) + min;
float f = (float)scaled;
Console.WriteLine(f);
}
}
}
}
``````

``````3.468961
8.04868
2.210197
8.150612
4.217263
5.328617
4.730082
8.462176
2.679844
8.609394
``````

在 C# 中使用 `Random.NextBytes()` 函数生成随机浮点数

``````using System;

namespace random_float {
class Program {
static void Main(string[] args) {
Random rand = new Random();
for (int i = 0; i < 10; i++) {
var array = new byte[4];
rand.NextBytes(array);
float randomFloat = BitConverter.ToSingle(array, 0);
Console.WriteLine("Random Value = {0}", randomFloat);
}
}
}
}
``````

``````Random Value = 2.021232E-20
Random Value = -121623
Random Value = -1.564382E+38
Random Value = 1.146448E-14
Random Value = -6.874067E-22
Random Value = -1.226989E+31
Random Value = -3.01435E+08
Random Value = -8.568415E+30
Random Value = -1.454825E+27
Random Value = 3.801608E-26
``````

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.