花了點時間寫了個數學運算式。

功能:輸入含有 +-*/%及()的數學式子,輸出答案。使用觀念:遞迴、字串操作、型別轉換

程式碼如下:( 歡迎指教~ )

using System;
using System.Collections.Generic;
using System.Text;
 
namespace 數學運算式 {
class MathFunc {
public static char[] d1 ={ '*', '/', '%' };
public static char[] d2 ={ '*', '/', '%', '+', '-' };
public static char[] d3 ={ '(', ')'};
public string[] temp;
public string test;
public char[] c1;
public int s1, s2, s3;
public int x1, x2, x3;
public int n1, n2;
public string MathPrase(string mp) {
c1 = mp.ToCharArray();
for (int i = 0; i < c1.Length; i++) {
if (c1[0] == '-') c1[0] = '~';
if (i != 0 && c1[i] == '-') {
if ("+_*/%".IndexOf(c1[i - 1]) != -1 || "+_*/%".IndexOf(c1[i + 1]) != -1) {
c1[i] = '~';
}
}
}
mp = new string(c1);
while (mp.IndexOfAny(d2) != -1) {
mp = new string(c1);
if ((temp = mp.Split(d2)).Length == 2) {
if (temp[0].StartsWith("~")) {
n1 = 0-Convert.ToInt16(temp[0].Trim('~').Trim('('));
} else {
n1 = Convert.ToInt16((temp[0].Trim('~').Trim('(')));
}
if (temp[1].StartsWith("~")) {
n2 = 0 - Convert.ToInt16(temp[1].Trim('~').Trim(')'));
} else {
n2 = Convert.ToInt16(temp[1].Trim('~').Trim(')'));
}
switch (mp.ToCharArray()[mp.IndexOfAny(d2)]) {
case '*':
mp = (n1 * n2).ToString();
break;
case '/':
mp = (n1 / n2).ToString();
break;
case '%':
mp = (n1 % n2).ToString();
break;
case '+':
mp = (n1 + n2).ToString();
break;
case '-':
mp = (n1 - n2).ToString();
break;
}
} else {
c1 = mp.ToCharArray();
int count;
if ((s1 = mp.IndexOfAny(d3)) != -1) {
count = 1;
s3 = s1;
while (count != 0) {
s2 = (mp.Substring(s3 + 1).IndexOfAny(d3) + s3 + 1);
if (c1[s2] == '(') count++;
else if (c1[s2] == ')') count--;
else { break; }
s3 = s2;
}
test = new MathFunc().MathPrase(mp.Substring(s1 + 1, (s2 - s1 - 1)));
if (mp.Length <= s2) {
mp = mp.Substring(0, s1)+test;
} else {
mp = mp.Substring(0, s1) + test + mp.Substring(s2 + 1);
}//遞迴
} else {
bool flag=false;
for (int i = 0; i < c1.Length; i++) {
if ("*%/".IndexOf(c1[i]) != -1) {
int k;
x2 = -1; x3 = -1;
for (int j = i - 1; j > 0; j--) {
if ("+-*/%".IndexOf(c1[j]) != -1) {
x2 = j;
break;
}
}
for (int j = i + 1; j < c1.Length; j++) {
if ("+-*/%".IndexOf(c1[j]) != -1) {
x3 = j;
break;
}
}
if (x3 == -1) x3 = mp.Length;
mp = mp.Insert(x2 + 1, "(").Insert(x3 + 1, ")");
flag=true;
break;
}
}
if (flag) { } else {
for (int i = 0; i < c1.Length; i++) {
if ("+-".IndexOf(c1[i]) != -1) {
int k;
x2 = -1; x3 = -1;
for (int j = i - 1; j > 0; j--) {
if ("+-*/%".IndexOf(c1[j]) != -1) {
x2 = j;
break;
}
}
for (int j = i + 1; j < c1.Length; j++) {
if ("+-*/%".IndexOf(c1[j]) != -1) {
x3 = j;
break;
}
}
if (x3 == -1) x3 = mp.Length;
mp = mp.Insert(x2 + 1, "(").Insert(x3 + 1, ")");
break;
}
}
}
}
}
c1 = mp.ToCharArray();
for (int i = 0; i < c1.Length; i++) {
if (c1[0] == '-') c1[0] = '~';
if (i != 0 && c1[i] == '-') {
if ("+_*/%".IndexOf(c1[i - 1]) != -1 || "+_*/%".IndexOf(c1[i + 1]) != -1) {
c1[i] = '~';
}
}
}
}
mp = mp.Replace('~', '-');
return mp;
}
}
}

 


 

arrow
arrow

    小新 發表在 痞客邦 留言(0) 人氣()