[英]Why does this lambda function return the wrong answer
I'm trying to convert an int array in C# to a normal integer It works for most numbers but when i have the following code:我正在尝试将 C# 中的 int 数组转换为普通的 integer 它适用于大多数数字,但是当我有以下代码时:
int[] digits = new int[] { 9,8,7,6,5,4,3,2,1,0 };
int bignumber = digits.Select((t, i) => t * Convert.ToInt32(Math.Pow(10, digits.Length - i - 1))).Sum();
it returns 1286608618 instead of 9876543210它返回 1286608618 而不是 9876543210
I imagine it has something to do with the length of the array?我想这与数组的长度有关吗? But I don't understand how... If I remove the 0 on the end and make the array 9 numbers long it works fine.
但我不明白如何......如果我删除最后的 0 并使数组长 9 个数字,它就可以正常工作。 Stick any number in the 10th position and it breaks again.
在第 10 个 position 中粘贴任何数字,它会再次中断。
Sum is going out of range of max Int32, which is 2147483647
. Sum 超出了最大 Int32 的范围,即
2147483647
。 Use Int64 (long) instead:改用 Int64(长):
int[] digits = new int[] { 9,8,7,6,5,4,3,2,1,0 };
long bignumber = digits.Select((t, i) => t * Convert.ToInt64(Math.Pow(10, digits.Length - i - 1))).Sum();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.