我正在计算字符串的内容。
我有一个字符串,其中包含: MyString = "1+5/2*4-2“,现在我要计算该字符串的结果
顺便说一句,我是c#的新手
我的代码:
string som = "";
int myInt;
private void getText_Click(object sender, EventArgs e)
{
string s = (sender as Button).Text;
som = som + s;
Console.WriteLine(som);
string[] words = som.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
myInt += Convert.ToInt32(word);
}
Console.WriteLine(myInt);我试过这个答案
double result = (double) new DataTable().Compute("1+1*4/2-5", null);
int i = (int) result; // -2但我得到了一个System.InvalidCastException:
指定的强制转换无效。
发布于 2017-09-20 11:50:26
您可以使用DataTable.Compute -“技巧”:
double result = (double) new DataTable().Compute("1+1*4/2-5", null);
int i = (int) result; // -2注释这里中提到了语法和支持的运算符。
https://stackoverflow.com/questions/46321256
复制相似问题