直接上代碼
實現思路:
1、首先小數點補 位,9223372036854775808.9+9223372036854775808.9223372036854775808 => 9223372036854775808.900000000000000000+9223372036854775808.9223372036854775808
2、然後開始按位進行計算,進位數放入jw,在下一位計算時加上
public static char[] Sum(string a, string b) { return Sum(a.ToCharArray(), b.ToCharArray()); } public static char[] Sum(char[] a, char[] b) { char[] c = a;//補位後的a char[] d = b;//補位後的b int alength = a.Count();//a長度 int blength = b.Count();//b長度 int adot = alength;//a小數點位置 int bdot = blength;//b小數點位置 #region 小數點補位 for (int i = 0; i < alength; i++) { if (a[i] == '.') { adot = i; break; } } for (int i = 0; i < blength; i++) { if (b[i] == '.') { bdot = i; break; } } if (adot != alength || bdot != blength) { if (adot == alength) { c = new char[alength + 1 + blength - bdot - 1]; for (int i = 0; i < c.Length; i++) { if (i < alength) { c[i] = a[i]; } else if (i == alength) { c[i] = '.'; } else { c[i] = '0'; } } } else if (bdot == blength) { d = new char[blength + 1 + alength - adot - 1]; for (int i = 0; i < d.Length; i++) { if (i < blength) { d[i] = b[i]; } else if (i == blength) { d[i] = '.'; } else { d[i] = '0'; } } } else { if (alength - adot > blength - bdot) { d = new char[blength + ((alength - adot) - (blength - bdot))]; for (int i = 0; i < d.Length; i++) { if (i < blength) { d[i] = b[i]; } else { d[i] = '0'; } } } else { c = new char[alength + ((blength - bdot) - (alength - adot))]; for (int i = 0; i < c.Length; i++) { if (i < alength) { c[i] = a[i]; } else { c[i] = '0'; } } } } } #endregion List<char> item = new List<char>(); int cl = c.Length; int dl = d.Length; int r = 0; int jw = 0;//進位 do { if (cl > 0 && dl > 0) { if (c[cl - 1] == '.') { r = '.'; } else { r = (int)c[cl - 1] + (int)d[dl - 1] - 96 + jw; jw = 0; if (r >= 10) { jw++; r = r - 10; } } } else if (cl <= 0 && dl > 0) { r = d[dl - 1] - 48+jw; jw = 0;
if (r >= 10)
{
jw++;
r = r - 10;
}
} else if (cl > 0 && dl <= 0) { r = c[cl - 1] - 48+jw;
jw = 0;
if (r >= 10)
{
jw++;
r = r - 10;
} } if (r == 46) { item.Add(Convert.ToChar(r)); } else { item.Add(Convert.ToChar(r.ToString())); } cl--; dl--; } while (cl > 0 || dl > 0); if (jw == 1) { item.Add('1'); } return item.ToArray(); }