C#中System.Random類的NextDouble()方法用於返回大於或等於0.0且小於1.0的隨機浮點數。
用法:
public virtual double NextDouble();
返回值:此方法返回一個大於或等於0.0且小於1.0的雙精度浮點數。
以下示例程序旨在說明NextDouble()方法的使用:
示例1:
// C# program to illustrate the
// Random.NextDouble() Method
using System;
class GFG {
// Driver code
public static void Main()
{
// Instantiate random number generator
Random rand = new Random();
// Print 10 random floating point numbers
Console.WriteLine("Printing 10 random floating point numbers");
for (int i = 0; i < 10; i++)
Console.WriteLine("{0} -> {1}", i, rand.NextDouble());
}
}
輸出:
Printing 10 random floating point numbers 0 -> 0.0227202852362396 1 -> 0.624568469647583 2 -> 0.0145442797870116 3 -> 0.646489209330869 4 -> 0.967497945748036 5 -> 0.839329582098559 6 -> 0.873648912121378 7 -> 0.16200648022909 8 -> 0.66018275761054 9 -> 0.0837694853934317
示例2:
// C# program to illustrate the
// Random.NextDouble() Method
using System;
class GFG {
// Driver code
public static void Main()
{
// Instantiate random number generator
Random rand = new Random();
// Instantiate an array of double
double[] a = new double[10];
// Store random floating point
// numbers in the array
for (int i = 0; i < 10; i++)
a[i] = rand.NextDouble();
// Print 10 random floating point numbers
Console.WriteLine("Printing 10 random "+
"floating point numbers");
for (int i = 0; i < 10; i++)
Console.WriteLine("{0} -> {1}", i, a[i]);
}
}
輸出:
Printing 10 random floating point numbers 0 -> 0.853536825558886 1 -> 0.741455778359182 2 -> 0.496043408986201 3 -> 0.0975164361752181 4 -> 0.120282317567748 5 -> 0.57163705703413 6 -> 0.749181974562435 7 -> 0.684014179596684 8 -> 0.691246760865323 9 -> 0.888019556127498
參考:
相關用法
- C# DateTimeOffset.Add()用法及代碼示例
- C# String.Contains()用法及代碼示例
- C# Math.Sin()用法及代碼示例
- C# Math.Cos()用法及代碼示例
- C# Dictionary.Add()用法及代碼示例
- C# Math.Tan()用法及代碼示例
- C# Math.Abs()方法用法及代碼示例
- C# Math.Exp()用法及代碼示例
- C# Math.Abs()函數用法及代碼示例
注:本文由純淨天空篩選整理自rupesh_rao大神的英文原創作品 C# | Random.NextDouble() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。