假设你有像1253999939979969998746和9999999999这样的大整数。在C#中是否有任何方法可以将这些大整数相乘?
注意:我已经尝试过System.Numerics.BigInteger类的构造函数,但编译器说“整数太长”。
你有什么建议吗?
附:如果这个问题不属于本主题,请警告我。
注意:我已经尝试过System.Numerics.BigInteger类的构造函数,但编译器说“整数太长”。
你有什么建议吗?
附:如果这个问题不属于本主题,请警告我。
BigInteger.Parse
。BigInteger num = BigInteger.Parse("1253999939979969998746");
如果您尝试像下面这样使用整数值
BigInteger num = 1253999939979969998746;
右侧需要一个类型,其默认情况下将是Int32
或long
。但由于数字太大而无法成为Int32
或long
,因此转换失败,因此出现错误。
如Tim Schmelter在评论中指出的那样,要进行乘法运算,可以执行以下操作:
BigInteger num = BigInteger.Multiply(BigInteger.Parse("1253999939979969998746"),
BigInteger.Parse("9999999999"));
BigInteger.Multiply
然后输入以下代码:BigInteger.Multiply( BigInteger.Parse("1253999939979969998746"), BigInteger.Parse("9999999999"));
。因为这是他所要求的,编译器错误修复只是其中一个问题。 - Tim Schmelter*
运算符被重载了,所以你也可以使用BigInteger result = bi1 * bi2;
。 - Tim SchmelterBigInteger类型是一个不可变类型,表示一个理论上没有上限或下限值的任意大的整数。
例子:
var num1 = BigInteger.Parse("1253999939979969998746");
var num2 = BigInteger.Parse("9999999999");
var result = BigInteger.Multiply(num1, num2);
注意:命名空间:System.Numerics
System.Numberics.BigInteger没有值的上限或下限。因此,BigInteger类可以处理您提到的数字。
编译器报错是因为您可能正在尝试从整数初始化BigInteger。您需要使用字节数组进行初始化或从字符串解析它。