gpt4 book ai didi

c# - 如何避免 DivideByZeroException

转载 作者:太空宇宙 更新时间:2023-11-03 23:16:31 26 4
gpt4 key购买 nike

您好,当我尝试在 GridView 中运行以下代码时,我遇到了这个错误Attempted to divide by zero

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

代码

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)
{

}
}

最佳答案

你应该使用 conditional operator (?:).

Profitprcn 行更改为:

decimal Profitprcn = Convert.ToDecimal(Purchase) ==0? 0 : (Profit * 100) / Convert.ToDecimal(Purchase);

关于c# - 如何避免 DivideByZeroException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37127261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com