首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何避免DivideByZeroException

如何避免DivideByZeroException
EN

Stack Overflow用户
提问于 2016-05-10 00:01:28
回答 2查看 490关注 0票数 1

嗨,当我试图在网格视图中运行下面的代码时,我得到了这个错误Attempted to divide by zero

当错误发生而不被除以零时,如何通过返回零作为除法来避免此错误。

代码语言:javascript
复制
protected void gridpandl_RowDataBound(object sender, GridViewRowEventArgs e)
{
    try
    {
        for (int index = 0; index < this.gridpandl.Rows.Count; index++)
        {
            string Purchase = GetPurchase(this.gridpandl.Rows[index].Cells[0].Text);
            string Sales = GetSales(this.gridpandl.Rows[index].Cells[0].Text);
            string Serivce = GetService(this.gridpandl.Rows[index].Cells[0].Text);
            decimal Profit = (Convert.ToDecimal(Sales) + Convert.ToDecimal(Serivce) - Convert.ToDecimal(Purchase));
            decimal Profitprcn = (Profit * 100) / Convert.ToDecimal(Purchase);
            this.gridpandl.Rows[index].Cells[2].Text = Purchase;
            this.gridpandl.Rows[index].Cells[3].Text = Sales;
            this.gridpandl.Rows[index].Cells[4].Text = Serivce;
            this.gridpandl.Rows[index].Cells[5].Text = Profit.ToString();
            this.gridpandl.Rows[index].Cells[6].Text = Math.Round(Profitprcn, 2).ToString();
        }

    }

    catch (DivideByZeroException ex)
    {

    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-05-10 00:04:15

您应该使用条件运算符(?:)

Profitprcn行更改为:

代码语言:javascript
复制
decimal Profitprcn = Convert.ToDecimal(Purchase) ==0? 0 : (Profit * 100) / Convert.ToDecimal(Purchase);
票数 8
EN

Stack Overflow用户

发布于 2016-05-10 00:10:08

就像这样:

代码语言:javascript
复制
decimal purchasesVal = 0;
decimal Profit = 0;
decimal Profitprcn = 0;

string Purchase = GetPurchase(this.gridpandl.Rows[index].Cells[0].Text);
string Sales = GetSales(this.gridpandl.Rows[index].Cells[0].Text);
string Serivce = GetService(this.gridpandl.Rows[index].Cells[0].Text);

if (!string.IsNullOrEmpty(Purchases) && Convert.ToDecimal(Purchase) > 0)
{
    purchasesVal = Convert.ToDecimal(Purchase);
    Profit = (Convert.ToDecimal(Sales) + Convert.ToDecimal(Serivce) - purchasesVal);
    Profitprcn = (Profit * 100) / purchasesVal;
}   
票数 -5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37127261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档