c# - 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
解决方案
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
withexps[1]
(with thex
substitutes in of course).
推荐阅读
- android - 当 RecyclerView 有一个项目然后屏幕适合时,PullRefreshLayout 闪烁并冻结
- ionic-framework - 未捕获的错误:添加导航时 ionic 中的模板解析错误
- python - 如何使用 selenium webdriver python 单击跨度文本
- javascript - 如何使用 Flask Jinja 模板生成内容和 JQuery Ajax 功能?
- java - 删除选定的 JTable 元素
- php - 创建 Excel 动态选项
- javascript - 从输入类型跳转到页面点=提交
- html - CSS在悬停时显示更大的图像
- sparql - SPARQL 查询中的元素组合
- java - 无法启动接收器 ClassCastException 无法转换为 retrofit2.Call