c# - 解析 BigInteger 时出现 FormatException

标签 c# parsing sum biginteger

我试图在 codewars.com 上解决一个问题,我在其中添加了两个 BitInteger。 Here is the Link

用我的代码:

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 错误:

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。

关于c# - 解析 BigInteger 时出现 FormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33718627/

相关文章:

c# - 转换绑定(bind)路径,以便它在设计时识别 ViewModel 属性

c# - 在 SQL CLR UDF 中使用 System.Linq 程序集

java - 为单个 DSL 生成两个解析器

parsing - 正在寻找 "tokenizer"、 "parser"和 "lexers"的明确定义以及它们如何相互关联和使用?

javascript - jQuery 求和或相乘值始终没有事件触发

c# - 需要在运行时转换 IQueryable<T>

c# - 从查询字符串中获取 UTC 日期时间

node.js - Nodejs 可读流,解析二进制数据,保留顺序

r - 使用 Rcpp 就地编辑后 sum 函数出现问题

javascript - 查找对象数组中的特定元素并将其添加