namespace Calculate2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Calculate_Click(object sender, EventArgs e)
{
string str = "";
StreamReader reader = new StreamReader(@"e:\a.txt"); //请提前建立a、b文件
StreamWriter writer = new StreamWriter(@"e:\b.txt");
while(!reader.EndOfStream)
{
str = reader.ReadLine();
int iResult = CalculateResult(str);
writer.WriteLine(str + iResult);
}
reader.Close();
writer.Close();
}
private int CalculateResult(string str)
{
string[] strNumbers = str.Split('+', '-', '*', '/', '=');
int j = strNumbers.Count() - 1;
int[] iNumber = new int[j];
int iNo = 0;
foreach (string strA in strNumbers)
{
if (strA == "")
{
break;
}
iNumber[iNo] = Convert.ToInt32(strA);
iNo++;
}
int iResult = 0;
int i = 0;
foreach (char ch in str)
{
switch (ch)
{
case '*':
iNumber[i] = iNumber[i] * iNumber[i + 1];
for (int k = i + 1; k < j - 1; k++)
{
iNumber[k] = iNumber[k + 1];
}
break;
case '/':
iNumber[i] = iNumber[i] / iNumber[i + 1];
for (int k = i + 1; k < j - 1; k++)
{
iNumber[k] = iNumber[k + 1];
}
break;
case '+':
case '-':
i++;
break;
default:
break;
}
}
iResult = iNumber[0];
i = 1;
foreach (char ch in str)
{
switch (ch)
{
case '+':
iResult += iNumber[i];
i++;
break;
case '-':
iResult -= iNumber[i];
i++;
break;
default:
break;
}
}
return iResult;
}
}
} |