【问题标题】:Get random number in int64 . (Big number) [duplicate]在 int64 中获取随机数。 (大号)[重复]
【发布时间】:2018-06-20 16:30:10
【问题描述】:

错误:

$exception {"对于 Int32,值要么太大要么太小。"} System.OverflowException

我的代码:

Random R = new Random();
if (NUD_1.Value > NUD_2.Value)
    return;
int v = R.Next((int)NUD_1.Value ,(int)NUD_2.Value);
    Label_generate2.Text = v.ToString();

我想生成数字。但是当我输入一个大数字时,它会给我这个错误。 NUD 是数字上下。

【问题讨论】:

  • 错误信息很清楚。 Random(int, int)only works with 32bit integers。你传递了 2 个 Int32 ,它返回一个 Int32
  • 那么就没有办法了吗?我怎样才能得到比最大的 int32 数字更大的数字。我想要 15 个字符。

标签: c#


【解决方案1】:

你要做的就是声明:

Int64 NUD_1Value = NUD_1.Value;
Int64 NUD_2Value = NUD_2.Value;

然后使用 NUD_1Value 代替 NUD.1Value

会有用的


编辑:

检查以下内容。它对我有用:

    Random R = new Random();

    double NUD_1Value = 1;
    double NUD_2Value = 999999999999999; //15-digit number

    var next = R.NextDouble();

    double v = NUD_1Value + (next * (NUD_2Value - NUD_1Value));

    MessageBox.Show(v.ToString());

【讨论】:

  • 最多可使用 14 位数字。当我做 15 位数时,这个错误就来了。 + $exception {"'minValue' 不能大于 maxValue。\r\n参数名称:minValue"} System.ArgumentOutOfRangeException
  • 编辑后:这个作品很好。谢谢你:)
  • 我写了一个测试方法,看到它返回冗余值。复制这些行并自己测试: [TestMethod] public void TestRand64() { Int64 rnum = 0; HashSet hs = new HashSet(); for (int i = 0; i
【解决方案2】:

试试:

long v = (long)Math.Round(NUD_1.Value + R.NextDouble() * ((double)NUD_2.Value - (double)NUD_1.Value));

【讨论】:

  • NUD 不是 double 而是 decimal 。它不起作用。
  • 我忘了先把小数转换成双倍。我已修改代码以包含此内容。
猜你喜欢
  • 2011-08-18
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 2018-05-15
  • 2015-03-22
  • 1970-01-01
  • 2010-12-12
相关资源
最近更新 更多