首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算字符串到int的内容

计算字符串到int的内容
EN

Stack Overflow用户
提问于 2017-09-20 11:49:21
回答 1查看 122关注 0票数 0

我正在计算字符串的内容。

我有一个字符串,其中包含: MyString = "1+5/2*4-2“,现在我要计算该字符串的结果

顺便说一句,我是c#的新手

我的代码:

代码语言:javascript
复制
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);

我试过这个答案

代码语言:javascript
复制
 double result = (double) new DataTable().Compute("1+1*4/2-5", null);
 int i = (int) result;  // -2

但我得到了一个System.InvalidCastException

指定的强制转换无效。

EN

回答 1

Stack Overflow用户

发布于 2017-09-20 11:50:26

您可以使用DataTable.Compute -“技巧”:

代码语言:javascript
复制
 double result = (double) new DataTable().Compute("1+1*4/2-5", null);
 int i = (int) result;  // -2

注释这里中提到了语法和支持的运算符。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46321256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档