首页 > 解决方案 > Two character Integer to char?

问题描述

So I am making a program that calculates X in an expression, e.g if I type 2*x=6 then it will say x = 3. My code:

  string[] exps = textBox1.Text.Split('=');
  DataTable dt = new DataTable();
  for (int i = 0; i < 50; i++)
  {
        string s = exps[0].Replace('x', Convert.ToChar(i.ToString())); //<- problem is there
        var v = dt.Compute(s, "");
        if (int.Parse(v.ToString()) == int.Parse(exps[1]))
        {
              listBox1.Items.Add("x = " + i);
              break;
        }
  }

But I have a problem when X is more than 9 (so it is two characters) e.g 12 or 27, It can't convert it to char. Can you help me how can I do this easier? Thank you!

And sorry for my bad English

标签: c#

解决方案


You don't have to use the Replace(char, char) overload. There is also a Replace(string, string) overload:

string s = exps[0].Replace("x", i.ToString());

You are probably aware of this already, but your way of solving equations only works for a very specific kind of equations. Mainly it has these problems:

  • the solution must be an integer between 0 and 49
  • there must be only one solution
  • Multiplication must be clearly indicated i.e. 5x doesn't mean 5 times x.
  • The right hand side must be an integer. This problem can be easily fixed by calling Compute with exps[1] (with the x substitutes in of course).

推荐阅读