</pre><pre name="code" class="csharp">今天写了一个科学计算器,实现了最基本的加减乘除乘方和一些函数,以线性格式输入。没写注释,仅供参考。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterScreen;
textBox1.Focus();
}
public void ActualMain()
{
try
{
string ep = textBox1.Lines[textBox1.Lines.Length-1];
filter(ref ep);
if (numOfCharInStr('(', ep) != numOfCharInStr(')', ep))
throw new Exception();
while (hasChar(ep, '('))
{
int L, R, j, LL;
string strfunc = "";
R = ep.IndexOf(')');
j = R - 1;
while (ep[j] != '(')
{ j--; }
L = j;
j--;
while (j >= 0 && j < ep.Length && ep[j] >= 97 && ep[j] <= 122)
{
strfunc += ep[j];
j--;
}
LL = j + 1;
reverseStr(ref strfunc);
if (strfunc == "")
ep = ep.Replace(ep.Substring(L, R - L + 1), jjcc(ep.Substring(L + 1, R - L - 1)));
else
{
string result = function(strfunc, Convert.ToDouble(jjcc(ep.Substring(L + 1, R - L - 1))));
ep = ep.Replace(ep.Substring(LL, R - LL + 1), result);
}
}
textBox1.AppendText("\n= " + jjcc(ep)+"\n");
textBox1.Focus();
textBox1.Select(textBox1.TextLength, 0);
textBox1.ScrollToCaret();
}
catch
{
MessageBox.Show("发生错误\n");
}
}
///转半角的函数(DBC case) <summary>
///转半角的函数(DBC case)
/// </summary>
/// <param name="input">任意字符串</param>
/// <returns>半角字符串</returns>
///<remarks>
///全角空格为12288,半角空格为32
///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
///</remarks>
public static string ToDBC(string input)
{
char[] c = input.ToCharArray();
for (int i = 0; i < c.Length; i++)
{
if (c[i] == 12288) { c[i] = (char)32; continue; }//全角空格
if (c[i] > 65280 && c[i] < 65375) { c[i] = (char)(c[i] - 65248); } //其他全角字符
}
return new string(c);
}
public static void filter(ref string eq)
{
eq = ToDBC(eq);
string process = "";
char[] terms = eq.ToCharArray();
for (int i = 0; i < eq.Length; i++)
{
int c = terms[i];
if ((c >= 97 && c <= 122 || (c >= 48 && c <= 57)) || c == '+' || c == '-' || c == '*' || c == '/' || c == '^'
|| c == '(' || c == ')' || c == '.'||c=='%'||c=='!')
{
process += terms[i];
}
}
eq = process;
}
public static void reverseStr(ref string str)
{
char[] chs = str.ToCharArray();
Array.Reverse(chs);
str = new string(chs);
}
public static string function(string str,double num)
{
double output=0;
if (str == "abs")
output = Math.Abs(num);
else if (str == "arccos")
output = Math.Acos(num);
else if (str == "arcsin")
output = Math.Asin(num);
else if (str == "arctan")
output = Math.Atan(num);
else if (str == "cos")
output = Math.Cos(num);
else if (str == "cosh")
output = Math.Cosh(num);
else if (str == "exp")
output = Math.Exp(num);
else if (str == "floor"