键盘输入问题 [英] Keyboard input problem
问题描述
I'm new to C# and I'm now doing scientific calculator assignment. Can you please help me from calculation from keyboard input in detail because my code doesn't work? I want to know all about from keyboard input.Also I don't know how to make multiopreation like 2+6+9-6*5. Sorry if I've grammar wrongs. Thank you so much all.
我的尝试:
What I have tried:
private void Main_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == Convert.ToChar(Keys.Escape))
{
txtDisplay.Clear();
}
if (e.KeyChar == Convert.ToChar(Keys.Back))
btnBack_Click(sender, e);
if ((txtDisplay.Text == "0") || eqClick == false)
{
switch (e.KeyChar.ToString())
{
case "+":
btnPlus.PerformClick();
break;
case "-":
btnMinus.PerformClick();
break;
case "*":
btnMultiply.PerformClick();
break;
case "/":
btnDivide.PerformClick();
break;
case "=":
btnEqual.PerformClick();
break;
case ".":btnDot.PerformClick();
break;
}
}
}
推荐答案
我讨厌说出来,但你做错了。
你有两个问题:首先是你在不需要的地方强迫点击事件 - 更好的解决方案是让您的click事件处理程序调用方法,然后从其他代码调用相同的方法。这将用户界面与处理代码分开,这意味着以后更容易更改。
第二个是你要做的不是真的要上班了。您举一个2 + 6 + 9-6 * 5作为多操作的示例,但您需要定义结果应该发生的事情:55或-13再进一步。
第一个结果是微不足道的:每次获得运算符时,都要先评估数据。所以你得到了
I hate to say it, but you are doing this all wrong.
You have two problems: the first is that you are "forcing" click events where you don't need to - a much better solution is to have your click event handlers call a method, and then call the same method from your other code. This separates the user interface from the processing code, which means it becomes a lot easier to change things later.
The second is that what you are trying to do is not really going to work. You give an example of "2+6+9-6*5" as a "multi-operation", but you would need to define what should happen as a result: 55, or -13 before you go any further.
The first result is trivial: each time you get an operator, you evaluate the data before it. So you get
2
2+ Evaluate: 2 == 2
2+6
2+6+ Evaluate: 2 + 6 == 8
8+9
8+9- Evaluate: 8 + 9 == 17
17-6
17-6* Evaluate: 17-6 == 11
11*5
11*5= Evaluate: 11*5 == 55
但是对于第二个你不能这样做因为你需要包含运算符优先级:*比+更重要所以你必须先评估(6 * 5)
然后再做其余的事情 - 这是一个更加复杂的负载。
我建议你看看其他计算器是如何工作的:不只是Calc.EXE,而是微软数学:从Microsoft官方下载中心下载Microsoft Mathematics 4.0 [ ^ ]并找出你的意思想要在乐之前实现到目前为止你已经完成了代码!
But for the second one your can't do that because you need to include operator precedence: "*" is "more important" than "+" so you have to evaluate (6*5)
before you can do the rest - and that is a whole load more complicated.
What I'd suggest is that you have a look at how other calculators work: not just Calc.EXE, but Microsoft Mathematics as well: Download Microsoft Mathematics 4.0 from Official Microsoft Download Center[^] and work out what you want to achieve before leaping into code as you have done so far!
这篇关于键盘输入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!