计算器使用单选按钮

时间:2013-11-16 22:47:14

标签: c# asp.net textbox radio-button calculator

我正在尝试使用asp.netc#中的单选按钮制作一个简单的计算器。每个文本框中输入两个数字,单击提交按钮并输入标签。 我得到的错误是当选中单选按钮并单击提交时,我收到运行时错误;任何人都可以帮助诊断为什么?

这是我的代码:

int total;

if (rbAdd.Checked)
{
    total = Convert.ToInt32(tbNo1.Text) + Convert.ToInt32(tbNo2.Text);
    lblAns2.Text = total.ToString();
}

if (rbMult.Checked)
{
    total = Convert.ToInt32(tbNo1.Text) * Convert.ToInt32(tbNo2.Text);
    lblAns2.Text = total.ToString();
}

2 个答案:

答案 0 :(得分:0)

仍然以相同方式失败的简化代码:

int total = 0;

int no1 = Convert.ToInt32(tbNo1.Text);
int no2 = Convert.ToInt32(tbNo2.Text);
if (rbAdd.Checked)
{
    total = no1 + no2;
}
else if (rbMult.Checked)
{
    total = no1 * no2;
}
lblAns2.Text = total.ToString();

答案 1 :(得分:0)

我已经尝试过您的代码,只有当我输入非整数值时才会收到错误消息(Input string was not in a correct format.),因为您的转换代码为Convert.ToInt32(tbNo1.Text);

您希望输入的值只是整数吗?如果是,请尝试使用此代码(修改自 John Saunders 代码):

int total = 0;
int no1 = Convert.ToInt32(Math.Round(decimal.Parse(tbNo1.Text), 0));
int no2 = Convert.ToInt32(Math.Round(decimal.Parse(tbNo2.Text), 0));
if (rbAdd.Checked)
{
    total = no1 + no2;
}
else if (rbMult.Checked)
{
    total = no1 * no2;
}
lblAns2.Text = total.ToString();

您还必须验证输入的值以保护无效字符。

否则,如果您不需要将输入的值转换为整数,则可以使用以下代码:

decimal total = 0;
decimal no1 = decimal.Parse(tbNo1.Text);
decimal no2 = decimal.Parse(tbNo2.Text);
if (rbAdd.Checked)
{
    total = no1 + no2;
}
else if (rbMult.Checked)
{
    total = no1 * no2;
}
lblAns2.Text = total.ToString();
相关问题