十进制值检查是否为零
我正在尝试编写一个除法方法,它接受 2 个参数。
public static decimal Divide(decimal divisor, decimal dividend)
{
return dividend / divisor;
}
现在,如果除数为 0,我们会得到不能被零除的错误,这没关系。
我想做的是检查除数是否为 0,如果是,则将其转换为 1。有没有办法在我的方法中不使用大量 if 语句的情况下执行此操作? 我认为很多 if() 会造成混乱。 我知道从数学上讲不应该这样做,但我还有其他功能。
例如:
if(divisor == 0)
{
divisor = 1;
}
return dividend / divisor;
可以不用if()
语句来完成吗?
I am trying to write a division method, which accepts 2 parameters.
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.
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.
For example:
if(divisor == 0)
{
divisor = 1;
}
return dividend / divisor;
Can it be done without the if()
statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这与 if 语句几乎相同,但更简洁。
This is pretty much the same as an if statement, but it is cleaner.
如果您确实想要的话,您可以创建自己的类型并重载 / 运算符以获得所需的行为。 实现隐式转换运算符以避免强制转换或类型转换。
然而,我认为这不是一个好主意,因为它会增加一些运行时开销; 唯一的好处是你会得到一些(可以说)看起来更干净的代码。
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.
您可以与
decimal.Zero
进行比较,例如somDecimalVar ==decimal.Zero
you can just compare to
decimal.Zero
likesomDecimalVar == decimal.Zero
您可以像这样执行条件 if 语句。 这与 VB.net 中的 IIF 相同。
请确保用 () 包裹后半部分,否则会出现除法错误。
You can do a conditional if statement like this. This is the same as IIF in VB.net
Make sure you wrap your second half with () or you will get a divide error.
通过使用
?:
运算符By using the
?:
operator