C# 高精度加法 支持小数
直接上代码实现思路:1、首先小数点补 位,9223372036854775808.9+9223372036854775808.9223372036854775808 => 9223372036854775808.900000000000000000+9223372036854775808.92233720368547758082、然后开始按位进行计算,进位数放入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 == '.') { adot = i; break; } } for (int i = 0; i < blength; i++) { if (b == '.') { bdot = i; break; } } if (adot != alength || bdot != blength) { if (adot == alength) { c = new char; for (int i = 0; i < c.Length; i++) { if (i < alength) { c = a; } else if (i == alength) { c = '.'; } else { c = '0'; } }
} else if (bdot == blength) { d = new char; for (int i = 0; i < d.Length; i++) { if (i < blength) { d = b; } else if (i == blength) { d = '.'; } else { d = '0'; } } } else { if (alength - adot > blength - bdot) { d = new char; for (int i = 0; i < d.Length; i++) { if (i < blength) { d = b; } else { d = '0'; } } } else { c = new char; for (int i = 0; i < c.Length; i++) { if (i < alength) { c = a; } else { c = '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 == '.') { r = '.'; } else { r = (int)c + (int)d - 96 + jw; jw = 0; if (r >= 10) { jw++; r = r - 10; } } } else if (cl <= 0 && dl > 0) { r = d - 48+jw; jw = 0; if (r >= 10) { jw++; r = r - 10; } } else if (cl > 0 && dl <= 0) { r = c - 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(); }
页:
[1]