C# 如何防止被零除?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10243382/
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
How to prevent division by zero?
提问by Mediator
ads = ads.Where(x => (x.Amount - x.Price) / (x.Amount / 100) >= filter.Persent);
if x.Amount == 0 I have error "Divide by zero error encountered."
如果 x.Amount == 0 我有错误“遇到除以零错误。”
like me in this request is to avoid?
像我这样的要求是为了避免?
update:
更新:
this helped, but I do not like the decision:
这有帮助,但我不喜欢这个决定:
ads = ads.Where(x => (x.Amount - x.Price) / ((x.Amount / 100)==0?0.1:(x.Amount / 100)) >= filter.Persent);
there is another way?
还有另一种方法吗?
采纳答案by Jon
ads = ads.Where(x => x.Amount != 0 &&
(x.Amount - x.Price) / (x.Amount / 100) >= filter.Persent);
回答by Julio Nobre
Of course, you can always implement a generic safe division method and use it all the way
当然,你可以随时实现一个通用的安全除法方法,并一路使用
using System;
namespace Stackoverflow
{
static public class NumericExtensions
{
static public decimal SafeDivision(this decimal Numerator, decimal Denominator)
{
return (Denominator == 0) ? 0 : Numerator / Denominator;
}
}
}
I have chosen decimaltype because it addresses all non nullable numeric types that I am aware of.
我选择了十进制类型,因为它解决了我知道的所有不可为空的数字类型。
Usage:
用法:
var Numerator = 100;
var Denominator = 0;
var SampleResult1 = NumericExtensions.SafeDivision(Numerator , Denominator );
var SampleResult2 = Numerator.SafeDivision(Denominator);

