数字以相反的顺序存储在数组中。这是一个应将两个数字a
和相加的函数,并将b
和存储在result
:
public static void SumDigitArraysDifferentSize(int[] a, int[] b, int[] result)
{
int length = Math.Max(a.Length, b.Length);
for (int i = 0; i < length; i++)
{
int lhs = (i < a.Length) ? a[i] : 0;
int rhs = (i < b.Length) ? b[i] : 0;
result[i] = (result[i] + lhs + rhs) % 10;
int carry = (result[i] + lhs + rhs) / 10;
for (int j = 1; carry > 0; j++)
{
result[i + j] = (result[i + j] + carry) % 10;
carry = (result[i + j] + carry) / 10;
}
}
}
但是,如果我添加例如:
static void Main(string[] args)
{
int[] lhs = { 9 }
int[] rhs = { 9, 9 };
int size = Math.Max(lhs.Length, rhs.Length) + 1;
int[] result = new int[size];
SumDigitArraysDifferentSize(lhs, rhs, result);
PrintArray(result);
}
结果是:
{ 8, 1, 1 }
而不是预期的:
{ 8, 0, 1 }
对于MCVE:
public static void PrintArray(int[] Array)
{
Console.Write("{");
int length = Array.Length;
for (int i = 0; i < length; i++)
{
Console.Write(Array[i]);
if (i < length - 1)
{
Console.Write(", ");
}
}
Console.Write("}\n");
}
您正在分配result[i]
,并在计算时再次使用结果carry
。
这:
result[i] = (result[i] + lhs + rhs) % 10;
int carry = (result[i] + lhs + rhs) / 10;
应该:
var sum = result[i] + lhs + rhs;
result[i] = (sum) % 10;
int carry = (sum) / 10;
与中的计算相同for (int j = 1; ...)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句