繁体   English   中英

解析BigInteger时格式异常

[英]FormatException when parsing BigInteger

我尝试在codewars.com上解决一个问题,我在其中添加了两个BitInteger。 链接在这里

用我的代码:

using System;
using System.Numerics;
using System.Globalization;

public static class Kata
{
    public static string sumStrings(string a, string b)
    {
      Console.WriteLine(a + " " + b);
      BigInteger numbera = BigInteger.Parse(a);
      BigInteger numberb = BigInteger.Parse(b);
      BigInteger numberc;

      numberc = numbera + numberb;
      Console.WriteLine(numberc);
      return numberc.ToString();
    }
}

我得到一个FormatException-Error:

System.FormatException : The value could not be parsed. 
at System.Numerics.BigNumber.ParseBigInteger (System.String value, NumberStyles style, System.Globalization.NumberFormatInfo info) [0x00000] in <filename unknown>:0 
at System.Numerics.BigInteger.Parse (System.String value) [0x00000] in <filename unknown>:0 
at Kata.sumStrings (System.String a, System.String b) [0x00000] in <filename unknown>:0 
at CodeWarsTest.Test6 () [0x00000] in <filename unknown>:0

但输出似乎是正确的。

input: string 1 --> "712569312664357328695151392" 
input: string 2 --> "8100824045303269669937"
output: sum --> 712577413488402631964821329

为什么我在这里得到一个FormatException?

编辑:该代码适用于MonoDevelopment,但不适用于Codewars.com网站。

这是他们网站的问题。 其中一个测试会为您传递第一个参数的无效输入(空字符串)。

以下是捕获此问题的代码:

BigInteger na, nb;
if (!BigInteger.TryParse(a, out na)) {
    Console.WriteLine("A is invalid: '{0}'",a);
}
if (!BigInteger.TryParse(b, out nb)) {
    Console.WriteLine("B is invalid: '{0}'", b);
}
var nc = na + nb;
return nc.ToString();

它打印

A is invalid: ''

测试编号为5。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM