如何解决c#中试图除以零的问题?

时间:2013-03-13 05:24:29

标签: c# textbox decimal division

我收到了这个bug, 我编写了如下代码

代码:

decimal Amnt;
decimal.TryParse(txtAmnt.Text, out Amnt);
int tnure=1;
int.TryParse(txtTnre.Text, out tnure);
txtDdctAmnt.Text = (Amnt /tnure).ToString("0.00");

当在文本框值0时我收到此错误。如果有可能给我答案。

4 个答案:

答案 0 :(得分:7)

如何在除以零之前简单地使用if进行检查?

if(tnure != 0)
    txtDdctAmnt.Text = (Amnt / tnure).ToString("0.00");
else
    txtDdctAmnt.Text = "Invalid value";

答案 1 :(得分:3)

检查tnure是否不为0,你得到零除零例,http://msdn.microsoft.com/en-us/library/ms173160.aspx提供更多帮助

decimal Amnt;
        decimal.TryParse(txtAmnt.Text, out Amnt);
        int tnure=1;
        int.TryParse(txtTnre.Text, out tnure);
if(tnure!=0)
{
        txtDdctAmnt.Text = (Amnt /tnure).ToString("0.00");
}
else
{
/*handle condition*/
}

答案 2 :(得分:1)

当tnre为0时,Amnt /tnure除以0.你需要在除法前检查tnre是否为0,如果它等于0则不要除以tnre。

答案 3 :(得分:0)

将您的代码放在try / Catch Statement中,就像这样

    try
    {
    decimal Amnt;
    decimal.TryParse(txtAmnt.Text, out Amnt);
    int tnure=1;
    int.TryParse(txtTnre.Text, out tnure);
    txtDdctAmnt.Text = (Amnt /tnure).ToString("0.00");
    }
    catch(Exception ex)
    {
        // handle exception here
        Response.Write("Could not divide any number by 0");
    }
相关问题