【问题标题】:how to solve attempted to divide by zero in c#? [closed]如何解决在c#中试图除以零的问题? [关闭]
【发布时间】:2013-03-13 05:24:28
【问题描述】:

我遇到了这个错误, 我在下面写了这样的代码

代码:

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 时,我收到此错误。如果可能,请给我答案。

【问题讨论】:

  • “解决”是什么意思?如果验证不是此处的选项,则在除法之前验证值或处理异常。我希望,您不要寻找一种允许除以零的方法。
  • 在除法运算发生前检查 'tnure!=0' 值。

标签: c# textbox decimal division


【解决方案1】:

在除以零之前简单地使用if 进行检查怎么​​样?

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

【讨论】:

    【解决方案2】:

    检查 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*/
    }
    

    【讨论】:

    • 感谢您尝试得到正确答案
    【解决方案3】:

    当tnre为0时,Amnt /tnure为0除。除之前需要检查tnre是否为0,等于0时不要除。

    【讨论】:

      【解决方案4】:

      像这样将你的代码放在 try/Catch 语句中

          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");
          }
      

      【讨论】:

      • 为什么要等待异常?你不能检查tnure吗?并且永远不要捕获全局 Exception 异常。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 2011-02-24
      • 2020-10-29
      • 2021-06-12
      • 2021-11-05
      相关资源
      最近更新 更多