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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15377666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:33:25  来源:igfitidea点击:

how to solve attempted to divide by zero in c#?

c#textboxdecimaldivision

提问by user1899761

I am getting this bug, I wrote code like this below

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

code:

代码:

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

when in textbox value 0 I am getting this error.If it is possible give answer to me.

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

采纳答案by Joachim Isaksson

How about simply using an ifto check before dividing by zero?

if在除以零之前简单地使用一个来检查怎么样?

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

回答by Cris

check if tnureis not 0,you are getting Divide by Zero Exception,more help at http://msdn.microsoft.com/en-us/library/ms173160.aspx

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

回答by Rajeev Kumar

Put your code in try/Catch Statement like this

像这样把你的代码放在 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");
    }

回答by Max Nanasy

When tnre is 0, Amnt /tnureis a division by 0. You need to check whether tnre is 0 before dividing, and don't divide by tnre if it is equal to 0.

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