C# 十进制值检查是否为零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/916224/
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
Decimal Value Check if Zero
提问by
I am trying to write a division method, which accepts 2 parameters.
我正在尝试编写一个除法方法,它接受 2 个参数。
public static decimal Divide(decimal divisor, decimal dividend)
{
return dividend / divisor;
}
Now, if divisor is 0, we get cannot divide by zero error, which is okay.
现在,如果除数为 0,我们得到不能被零除的错误,这没关系。
What I would like to do is check if the divisor is 0 and if it is, convert it to 1. Is there way to do this with out having a lot of if statements in my method? I think a lot of if()s makes clutter. I know mathematically this should not be done, but I have other functionality for this.
我想要做的是检查除数是否为 0,如果是,则将其转换为 1。有没有办法在我的方法中没有很多 if 语句的情况下做到这一点?我认为很多 if() 会造成混乱。我知道数学上不应该这样做,但我有其他功能。
For example:
例如:
if(divisor == 0)
{
divisor = 1;
}
return dividend / divisor;
Can it be done without the if()
statement?
可以不用if()
声明吗?
采纳答案by CodeLikeBeaker
You can do a conditional if statement like this. This is the same as IIF in VB.net
您可以执行这样的条件 if 语句。这与VB.net中的IIF相同
return dividend / ((divisor == 0) ? 1 : divisor);
Make sure you wrap your second half with () or you will get a divide error.
确保你用 () 包裹你的后半部分,否则你会得到一个除法错误。
回答by Brandon
This is pretty much the same as an if statement, but it is cleaner.
这与 if 语句几乎相同,但更简洁。
return dividend / divisor == 0 ? 1 : divisor;
回答by Jakub ?turc
By using the ?:
operator
通过使用?:
运算符
return (divisor == 0) ? dividend : dividend / divisor
回答by driis
You could create your own type and overload the / operator to get the desired behaviour, if you really want. Implement the implicit conversion operators to avoid casting or type converting.
如果您真的想要,您可以创建自己的类型并重载 / 运算符以获得所需的行为。实现隐式转换运算符以避免强制转换或类型转换。
I don't think it would be a good idea, however, since it would add some runtime overhead; with the only benefit that you get some code that (arguably) looks a little cleaner.
但是,我认为这不是一个好主意,因为它会增加一些运行时开销;唯一的好处是你得到了一些(可以说)看起来更干净的代码。
回答by seekingtheoptimal
you can just compare to decimal.Zero
like somDecimalVar == decimal.Zero
你可以比较decimal.Zero
喜欢somDecimalVar == decimal.Zero