Get a random floating-point number between 0.0 and 1.0 in CSharp

Description

The following code shows how to get a random floating-point number between 0.0 and 1.0.

Example


/*from  ww  w .j a  v a  2 s . c  o  m*/
using System;

public class RandomProportional : Random
{
    protected override double Sample( )
    {
        return Math.Sqrt( base.Sample( ) );
    }

    public override int Next()
    {
       return (int) (Sample() * int.MaxValue);
    }   
}

public class RandomSampleDemo  
{
    static void Main( )
    {  
        RandomProportional randObj = new RandomProportional( );

        for( int j = 0; j < 10; j++ ){
           Console.WriteLine(randObj.NextDouble( ) );
        }

        for( int j = 0; j < 10; j++ ){
           Console.Write( "{0,12}", randObj.Next( ) );
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Development »




Console
Encoding
Environment
Random