C#學習8:建一個WPF文件,實現表達式求值,界面比較簡陋,添加了一張背景圖片,添加背景圖片的代碼是
[csharp]
<Grid.Background>
<ImageBrush ImageSource="/表達式求值;component/Images/1.jpg" />
</Grid.Background>
再修改background的屬性即可
輸入的表達式形如:((1+2)*5+1)/4=
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace 表達式求值
{
/// <summary>
/// MainWindow.xaml 的交互邏輯
/// </summary>
public partial class MainWindow : Window
{
int[,] map = new int[7, 7] { {1,1,-1,-1,-1,1,1}, // 算符間的優先關系
{1,1,-1,-1,-1,1,1},
{1,1,1,1,-1,1,1},
{1,1,1,1,-1,1,1},
{-1,-1,-1,-1,-1,0,100},
{1,1,1,1,100,1,1},
{-1,-1,-1,-1,-1,100,0}
};
char[]str=new char[1005];
char[]optr = new char[1005];
double[]opnd = new double[1005];
int t1, t2, k, len;
char ch, zz;
int temp1, temp2;
double a, b;
public MainWindow()
{
InitializeComponent();
}
public int cam(char c)
{
switch (c)
{
case '+': return 0;
case '-': return 1;
case '*': return 2;
case '/': return 3;
case '(': return 4;
case ')': return 5;
case '#': return 6;
default: return -1;
}
}
public double sol(double x, char c, double y)
{
switch (c)
{
case '+': return x + y;
case '-': return x - y;
case '*': return x * y;
case '/': return x / y;
default: return -1;
}
}
public int z(char c)
{
if ('0' <= c && c <= '9' || c == '.')
return 1;
if (c == ' ')
return -1;
return 0;
}
private void button2_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
string s = resource.Text;
str = s.ToCharArray();
len = s.Length;
str[len - 1] = '#'; //處理等於號
t1 = t2 = k = 0;
optr[t1++] = '#';
ch = str[k++];
while (ch != '#' || optr[t1 - 1] != '#')
{
if (z(ch) == 1) //操作數入棧
{
double num1,num2,sm;
int t,flagg;
num1=num2=0;
t=k-1;
flagg=0;
sm=0.1;
while (z(str[t]) == 1)
{
if (str[t] == '.')
{
flagg = 1;
t++;
continue;
}
if (flagg == 0)
num1 = num1 * 10 + (str[t] - '0');
else
{
num2 += sm * (str[t] - '0');
sm *= 0.1;
}
t++;
}
opnd[t2++] =num1+num2; //把字符串轉換成浮點數
k = t;
ch = str[k++];
}
else if (z(ch) == -1)
ch = str[k++];
else
{
temp1 = cam(optr[t1 - 1]);
temp2 = cam(ch);
if (map[temp1,temp2] == -1) //棧頂元素優先權低
{
optr[t1++] = ch;
ch = str[k++];
}
else if (map[temp1,temp2] == 0) //脫括號並接受下一個字符
{
t1--;
ch = str[k++];
}
else //退棧並將運算結果
{
zz = optr[--t1];
a = opnd[--t2];
b = opnd[--t2];
opnd[t2++] = sol(b, zz, a);
}
}
}
result.Text = opnd[0].ToString();
}
}
}