C# 高精度加法 支持小数(待优化)

直接上代码

实现思路:

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 = ; i < alength; i++)
{
if (a[i] == '.')
{
adot = i;
break;
}
}
for (int i = ; i < blength; i++)
{
if (b[i] == '.')
{
bdot = i;
break;
}
}
if (adot != alength || bdot != blength)
{
if (adot == alength)
{
c = new char[alength + + blength - bdot - ];
for (int i = ; i < c.Length; i++)
{
if (i < alength)
{
c[i] = a[i];
}
else if (i == alength)
{
c[i] = '.';
}
else
{
c[i] = '';
}
} }
else if (bdot == blength)
{
d = new char[blength + + alength - adot - ];
for (int i = ; i < d.Length; i++)
{
if (i < blength)
{
d[i] = b[i];
}
else if (i == blength)
{
d[i] = '.';
}
else
{
d[i] = '';
}
}
}
else
{
if (alength - adot > blength - bdot)
{
d = new char[blength + ((alength - adot) - (blength - bdot))];
for (int i = ; i < d.Length; i++)
{
if (i < blength)
{
d[i] = b[i];
}
else
{
d[i] = '';
}
}
}
else
{
c = new char[alength + ((blength - bdot) - (alength - adot))];
for (int i = ; i < c.Length; i++)
{
if (i < alength)
{
c[i] = a[i];
}
else
{
c[i] = '';
}
}
}
}
} #endregion List<char> item = new List<char>();
int cl = c.Length;
int dl = d.Length;
int r = ;
int jw = ;//进位
do
{
if (cl > && dl > )
{
if (c[cl - ] == '.')
{
r = '.';
}
else
{
r = (int)c[cl - ] + (int)d[dl - ] - + jw;
jw = ;
if (r >= )
{
jw++;
r = r - ;
}
}
}
else if (cl <= && dl > )
{
r = d[dl - ] - 48+jw;
            jw = 0;
                    if (r >= 10)
                    {
                        jw++;
                        r = r - 10;
                    }
}
else if (cl > && dl <= )
{
r = c[cl - ] - 48+jw;
            jw = 0;
                    if (r >= 10)
                    {
                        jw++;
                        r = r - 10;
                    }
} if (r == )
{
item.Add(Convert.ToChar(r));
}
else
{
item.Add(Convert.ToChar(r.ToString()));
}
cl--; dl--;
} while (cl > || dl > );
if (jw == )
{
item.Add('');
}
return item.ToArray();
}
上一篇:Linux中Mysql的简介和安装


下一篇:html-----003