c# - 如何让我的计算器进行多次计算?(C#)
问题描述
我使用 Visual Studio 和 C# 编程语言创建了一个计算器。一切都很好,除了一件事。
我不能让计算器一次做多个计算(例如:3 + 3),我希望它可以做 3 + 3 + 3 + 3,但我不知道该怎么做。
(我把你应该感兴趣的代码留在下面)
private void click_operazione(object sender, EventArgs e)
{
double i;
if (double.TryParse(textBox1.Text, out i))
{
Button b = (Button)sender;
Operazione = b.Text;
numero = double.Parse((textBox1.Text));
hapremuto_operazione = true;
textBox2.Text = numero + " " + Operazione;
}
}
private void risultato_click(object sender, EventArgs e)
{
hapremuto_uguale = true;
switch (Operazione)
{
case "+":
risultato = (numero + double.Parse(textBox1.Text)).ToString();
textBox2.Text = textBox2.Text + " " + textBox1.Text;
textBox1.Text = risultato;
textBox2.Text = textBox2.Text + " = " + risultato;
break;
case "-":
risultato = (numero - double.Parse(textBox1.Text)).ToString();
textBox2.Text = textBox2.Text + " " + textBox1.Text;
textBox1.Text = risultato;
textBox2.Text = textBox2.Text + " = " + risultato;
break;
case "x":
risultato = (numero * double.Parse(textBox1.Text)).ToString();
if (risultato.Length <= 15)
{
textBox2.Text = textBox2.Text + " " + textBox1.Text;
textBox1.Text = risultato;
textBox2.Text = textBox2.Text + " = " + risultato;
}
else
{
textBox1.Text = "errore";
textBox2.Text = "errore";
}
break;
case ":":
risultato = (numero / double.Parse(textBox1.Text)).ToString();
textBox2.Text = textBox2.Text + " " + textBox1.Text;
textBox1.Text = risultato;
textBox2.Text = textBox2.Text + " = " + risultato;
break;
case "%":
risultato = ((numero * double.Parse(textBox1.Text)) / 100).ToString();
textBox2.Text = textBox2.Text + " " + textBox1.Text;
textBox1.Text = risultato;
textBox2.Text = textBox2.Text + " = " + risultato;
break;
}
ha_appena_messo_una_virgola = false;
}
我还没有尝试任何东西,我没有想到任何想法
解决方案
You can create a delegate
that accepts a method reference for you calculation
See Delegates.
public delegate double CalculateExpression(double value1, double value2);
You then then need to create methods that have the same parameter list as the delegate and same return type.
For example this will multiply:
Overall, I would suggest looking into delegates to solve this problem.
public double Multiply(double value1, double value2)
{
return value1 * value2;
// add validation and etc. if needed instead of returning
// immediately .
}
Creating and using this delegate in the calling method.
var calcExpression = new CalculateExpression(Multiply);
double result = calcExpression(10, 10); // result is 100.
推荐阅读
- mysql - MySQL btr_search_guess_on_hash 高负载
- django - Django-dsl-drf 排除短语查询
- spring - keycloak中的自定义oidc
- python - 我在 selenium 中遇到错误。我有最新版本的 Chrome:87.0.4280.66。Selenuim Chrome 版本:87
- sql - 为什么代码“ORDER BY rating DESC”会导致我的代码出错?
- r - R 表产生意想不到的结果
- javascript - 有没有办法让函数记住以前的结果?
- unity3d - 如何统一向多维数据集添加文本
- google-cloud-firestore - 有没有办法强制 Firestore 文档包含真实的元数据?
- linear-regression - 在 lmer 中解释两个交互项的影响的正确方法是什么?