番茄零乱初学c#之字符串加减乘
时间:2010-11-13 来源:番茄零乱
记录下自己学编程的点点滴滴。
暂时不支持除法,还没找到好的解决办法。
static string SuperCalc(string a, string b,char op)
{ string temp = ""; 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 = new string('0', al - bl) + b; else a = new string('0', bl - al) + a; } if(op=='*') { string temps = ""; for (int i = a.Length - 1; i >= 0; i--) { carry = 0; temp= ""; Da = a[i] - 48; for (int j = b.Length - 1; j >= 0; j--) { Db = b[j] - 48; am = Da*Db +carry; if (am > 9) carry = am / 10; else carry = 0; //拼接 temp = (am % 10).ToString() + temp; } if (carry != 0) temp = carry + temp; temps= SuperAdd(temps, temp+new string('0',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;//可以作为减法 //判断是否有进位 if (am > 9) carry = am / 10; else carry = 0; //拼接 temp = (am%10).ToString() + temp; } if (carry != 0) temp=carry + temp; return temp ; }
相关阅读 更多 +