我想在文本框中显示答案,请帮助我需要严重
示例:
public void compute1(double n1, double n2, string opr)
{
if (opr == "-")
{
ans = (n1 - n2);
}
}
private void cmbOperator_SelectedIndexChanged(object sender, EventArgs e)
{
double var1 = Convert.ToDouble(txtFirstOperand.Text);
double var2 = Convert.ToDouble(txtSecondOperand.Text);
if (cmbOperator.Text == "+" || cmbOperator.Text == "-")
{
txtResult.Text = compute1(var1, var2, opr1); //Heres the Error i want to show the answer in the box
}
}
答案 0 :(得分:2)
public double compute1(double n1, double n2, string opr)
{
if (opr == "-")
{
return n1 - n2;
}
return null
}
可用性:
if (cmbOperator.Text == "+" || cmbOperator.Text == "-")
{
txtResult.Text = (compute1(var1, var2, opr1)).ToString();
}
的变化:
在您的compute1
方法中,我们已将type
从void
更改为double
。这意味着无论何时调用方法并向其传递必要的参数,即compute1(1.22, 4.22, -);
,它将return
计算出的数字作为类型double
然后我们将其转换为String
类型使用Convert.ToString()
使其成为文本框的正确type
。
如果运算符不匹配,则该方法将返回null
。
答案 1 :(得分:1)
如果要分配在方法中计算的内容,则该方法需要返回类型。它不应该是无效的。
public string compute1(double n1, double n2, string opr)
{
var ans = "";
if (opr == "-")
{
ans = (n1 - n2).ToString();
}
return ans;
}
private void cmbOperator_SelectedIndexChanged(object sender, EventArgs e)
{
double var1 = Convert.ToDouble(txtFirstOperand.Text);
double var2 = Convert.ToDouble(txtSecondOperand.Text);
if (cmbOperator.Text == "+" || cmbOperator.Text == "-")
{
txtResult.Text = compute1(var1, var2, opr1); //Heres the Error i want to show the answer in the box
}
}
要将其分配给文本框的文本值,我建议您将其作为字符串返回。如果需要,您也可以将其作为double返回,在这种情况下,从上面的代码中删除ToString()
并将返回值设置为double。
答案 2 :(得分:0)
将方法返回类型更改为double?
(Nullable double)并返回您计算的值。如果您的if条件返回null
false
作为后备
public double? compute1(double n1, double n2, string opr)
{
if (opr == "-")
{
return (n1 - n2);
}
else if (opr == "+")
{
return (n1 + n2);
}
return null; // fallback
}
现在,当你调用时,在检查它是否为null之后,将此方法调用的结果设置为教科书的Text属性
double? result = compute1(var1, var2, opr1);
if(result!=null)
{
txtResult.Text = result.Value.ToString();
}
答案 3 :(得分:0)
首先让你的函数实际返回一个结果:
public double compute1(double n1, double n2, string opr)
{
if (opr == "-")
{
return (n1 - n2);
}
return 0.0; // or throw an exception? some other behavior?
}
然后您可以使用返回的值:
txtResult.Text = compute1(var1, var2, opr1).ToString();