【问题标题】:Cannot implicitly convert type 'System.Numerics.BigInteger' to 'int'. An explicit conversion exists (are you missing a cast?)无法将类型“System.Numerics.BigInteger”隐式转换为“int”。存在显式转换(您是否缺少演员表?)
【发布时间】:2018-05-11 19:21:14
【问题描述】:

我有一个数组和一个简单的循环:

static BigInteger[] dataSet = new BigInteger[] { 100913, 1009139, 10091401, 100914061, 1009140611, 10091406133, 100914061337, 1009140613399 };


 foreach (BigInteger num in dataSet ) {

                BigInteger[] Vector = new BigInteger[num];

                for (BigInteger i = 1; i <= num; i++)  {
                    Vector[i - 1] = i;
                }
            }

谁能解释为什么这段代码返回

无法将类型“System.Numerics.BigInteger”隐式转换为“int”。 存在显式转换(您是否缺少演员表?)

此行出现错误:

BigInteger[] Vector = new BigInteger[num]; 

一切都转换为BigInteger,我看不出可能的原因。

感谢您的帮助,

提前致谢,

【问题讨论】:

  • 错误在哪一行?
  • BigInteger[] Vector = new BigInteger[num];
  • numBigInteger 但您正在使用它来初始化数组的大小。
  • 没错,因为我想创建与 num 大小相同的数组
  • 是的,据我所知,BigInteger 使用(至少)16 个字节,这意味着您要在此处创建的最大数组大约是 16gb 内存!

标签: c# .net


【解决方案1】:

numBigInteger,但您正在使用它来初始化数组的大小:

BigInteger[] Vector = new BigInteger[num];

数组的索引器是int,这意味着您可以创建的最大大小是int.MaxValue (2,147,483,647)。

【讨论】:

    【解决方案2】:

    我建议放弃以您使用的方式使用BigInteger 的想法,因为您将耗尽内存分配数组的值高于int.MaxValue。出于某种目的,数组和列表仅限于 int.MaxValue。如果在 99.9% 的情况下使用数组,整数将满足您的需求。

    我想知道你要归档什么,为什么需要这么大的数组,只需要递增的计数器?

    为了使您的代码编译,您需要转换您的 BigIntegers:

             foreach (BigInteger num in dataSet ) {
    
                BigInteger[] Vector = new BigInteger[(int)num];
    
                for (BigInteger i = 1; i <= num; i++)  {
                    Vector[(int)(i - 1)] = i;
                }
            }
    

    但是您的代码很可能由于内存不足或超出范围异常而失败,因为 BigInteger > Integer。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多