- 注册时间
- 2004-8-28
- 最后登录
- 1970-1-1
|
写的不好,大家经管拍砖……。但是,请表说废话~~
类里面的两个主要部分
【calculate方法】:
输入一个字符串,只包含字符和四则运算符,返回结果。如果有非法字符,返回原字符串。主要是自己的程序里面需要这样的处理。如果要返回数字,直接调用workout方法就可以。
【workout方法】:
输入一个字符串,只包含字符和四则运算符,返回一个numitem类,包含运算符和值。
public class Calculate
{
public class ops
{
public string name="";
public int level=0;
public ops(string iname,int ilevel){level=ilevel;name=iname;}
}
public class numItem
{
public int num,next;
public ops op=new ops("",0);
}
public ops[] operators=
{
new ops("(",1),
new ops(")",1),
new ops("+",2),
new ops("-",2),
new ops("*",3),
new ops("/",3)
};
public string calculate(string str)
{
for(int i=0;i<str.Length;i++)
{
if((str>='a'&&str<='z')||(str>='A'&&str<='Z')) return str;
if(str<'0'||str>'9')
{
bool isWrong=true;
foreach(ops j in operators)
{
if(j.name==str.Substring(i,j.name.Length)){isWrong=false;break;}
}
if(isWrong==true) return str;
}
}
return workout(str,0).num.ToString();
}
//返回数字和它前面的符号
private numItem getone(string str,int p)
{
numItem one=new numItem();
//取数字
int s=0;
while( p+s<str.Length && str[p+s]<='9' && str[p+s]>='0') s++;
one.next=p+s;
for(int i=1;s>0;s--)
{
one.num+=(str[p+s-1]-'0')*i;
i*=10;
}
//取算符
p=one.next;
foreach(ops i in operators)
{
if(p<str.Length && str.Substring(p,i.name.Length)==i.name)
{
one.op=i;
p+=i.name.Length;
break;
}
}
one.next=p;
if(one.op.name=="(") one=workout(str,one.next);
return one;
}
public numItem workout(string str,int p)
{
numItem one=getone(str,p);
int result=one.num;
while(true)
{
numItem next=getone(str,one.next);
if(next.op.level>one.op.level) next=workout(str,one.next);
//运算
if(one.op.name=="+")
{
result=next.num+one.num;
}
else if(one.op.name=="-")
{
result=one.num-next.num;
}
else if(one.op.name=="*")
{
result=next.num*one.num;
}
else if(one.op.name=="/")
{
result=one.num/next.num;
}
one=next;
one.num=result;
if(next.op.name=="") return one;
if(next.op.name==")")
{
one=getone(str,next.next);
one.num=result;
return one;
}
}
}
}
[此贴子已经被作者于2005-1-18 15:15:19编辑过]
|
|