閒來沒事有點無聊,記得以前搞acm時經常用c來寫無限位數的加減計算,那乘除呢?我現在就用c#寫了一個:
加法和減法簡單,就是用一個數組來保存每一位上的數字,然後從後往前一位一位的加減,加法記得前面會進一,減法則要把前面多余的“0”去掉;
乘法,你就在草稿紙上做下筆算吧,就是兩個數組相應位數撒謊能夠的數字相乘,分別在後面加上這兩個數位後面的“0”,比如:
234*678=2*6*100*100+2*7*100*10+。。。。+4*8
是否看的明白?就是小學時老師怎麼教你算你就怎麼算,把電腦當成小學生就行了,這裡要用到前面的加法;
除法:先拿被除數前面和除數相同位數的數和除數的倍數進行比較,這裡的倍數計算就是前面的乘法,把最大倍數放進答案的最高位,以此類推,再把余下的數*10+後面一位,繼續計算,直到最後一位;
下面是我寫的代碼,我先貼出最底層的無符號無浮點運算,計算參數均為StringBuilder類型,方便轉換
(此代碼僅供參考,不得參與商業活動)
static internal class Calculate
{
static private int[] operand1;
static private int[] operand2;
static private IList<int> result;
/// <summary>
/// 加法
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
static internal StringBuilder Addition(StringBuilder a, StringBuilder b)
{
SetOperand(a, b);
try
{
Reverse();
int count = (operand1.Length > operand2.Length) ? operand1.Length : operand2.Length;
int op1, op2, upNum = 0;
for (int i = 0; i < count; i++)
{
op1 = (i >= operand1.Length) ? 0 : operand1[i];
op2 = (i >= operand2.Length) ? 0 : operand2[i];
int temp = op1 + op2 + upNum;
if (temp < 10)
{
result.Insert(0, temp);
upNum = 0;
}
else
{
result.Insert(0, temp % 10);
upNum = temp / 10;
}
if ((i == (count - 1)) && upNum > 0) result.Insert(0, upNum);
}
}
catch { result = new List<int>() { 0,0,0}; }
return GetResult();
}
/// <summary>
/// 減法
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
static internal StringBuilder Subtraction(StringBuilder a, StringBuilder b)
{
SetOperand(a, b);
try
{
Reverse();
bool desc = isDesc(a, b);
int[] opList1 = desc ? operand2 : operand1;
int[] opList2 = desc ? operand1 : operand2;
int count = (opList1.Length > opList2.Length) ? opList1.Length : opList2.Length;
int op1, op2, upNum = 0;
for (int i = 0; i < count; i++)
{
op1 = (i >= opList1.Length) ? 0 : opList1[i];
op2 = (i >= opList2.Length) ? 0 : opList2[i];
&