记录下自己学编程的点点滴滴。
暂时不支持除法,还没找到好的解决办法。
static string SuperCalc(string a, string b, char op)
{
StringBuilder temp = new StringBuilder();
int carry = 0, Da, Db;//进位数,转换成数字的A和B
int al = a.Length, bl = b.Length;//操作数的长度(位数)
int am = 0;//每次计算的结果
//根据运算条件补充0
if (op == '+' || op == '-')
{
if (al > bl) b = b.PadLeft(al, '0');
else a = a.PadLeft(bl, '0');
}
if (op == '*')
{
string temps = "";
for (int i = a.Length - 1; i >= 0; i--)
{
carry = 0;
temp.Clear();
Da = a[i] - 48;
for (int j = b.Length - 1; j >= 0; j--)
{
Db = b[j] - 48;
am = Da * Db + carry;
carry = am / 10;
//拼接
temp.Insert(0, (am % 10).ToString());
}
if (carry != 0) temp.Insert(0, carry);
temps = SuperCalc(temps, temp.ToString() + new string('0', a.Length - 1 - i), '+');
}
return temps;
}
for (int i = a.Length - 1; i >= 0; i--)
{
Da = a[i] - 48;
Db = b[i] - 48;
if (op == '+') am = Da + Db + carry;//算出相加并进位后的数,此处做加法
if (op == '-') am = Da - Db - carry;//可以作为减法
//判断是否有进位
carry = am / 10;
if (am < 0)
{
carry = 1;
am = 10 + am;
}
//拼接
temp.Insert(0,(am % 10).ToString() );
}
if (carry != 0) temp.Insert(0, carry);
return temp.ToString();
}
static string SuperAdd(string a, string b)
{
StringBuilder result= new StringBuilder();
int aLen = a.Length, bLen = b.Length,c=0, ab = 0;
if (aLen > bLen) b = b.PadLeft(aLen, '0');//补充0操作
else a=a.PadLeft(bLen, '0');
for (int i = a.Length-1; i >= 0; i--)
{
ab = a[i] + b[i] - 96 + c;//算出单项之和
c = ab/10;//保存进位
result.Insert(0, ab % 10);//将单项之和求余保存至字符串的最前
}
if (c != 0) result.Insert(0, "1");//判断最后一次是否有进位,如有就加到最前面
return result.ToString();
}