在 C# 中生成随机十进制 [英] Generating a Random Decimal in C#

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

问题描述

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

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

推荐答案

删除旧版本

这类似于 Daniel 的版本,但会提供完整的范围.它还引入了一种新的扩展方法来获取随机的任意整数"值,我认为这很方便.

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)
{
     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天全站免登陆