生成在C#中的任意十进制 [英] Generating a Random Decimal in C#

查看:246
本文介绍了生成在C#中的任意十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能得到一个随机System.Decimal? System.Random 不直接支持它。

How can I get a random System.Decimal? System.Random doesn't support it directly.

推荐答案

编辑:删除旧版本

这是类似丹尼尔的版本,但会给完整范围。它还引入了一个新的扩展方法来获得一个随机任何整数的价值,我认为这是很方便的。

This is similar to Daniel's version, but will give the complete range. It also introduces a new extension method to get a random "any integer" value, which I think is handy.

注意小数这里分布的不统一

/// <summary>
/// Returns an Int32 with a random value across the entire range of
/// possible values.
/// </summary>
public static int NextInt32(this Random rng)
{
     unchecked
     {
         int firstBits = rng.Next(0, 1 << 4) << 28;
         int lastBits = rng.Next(0, 1 << 28);
         return firstBits | lastBits;
     }
}

public static decimal NextDecimal(this Random rng)
{
     byte scale = (byte) rng.Next(29);
     bool sign = rng.Next(2) == 1;
     return new decimal(rng.NextInt32(), 
                        rng.NextInt32(),
                        rng.NextInt32(),
                        sign,
                        scale);
}

这篇关于生成在C#中的任意十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆