Decimal value Check for a zero

I am trying to write a separation method that takes 2 parameters.

public static decimal Divide(decimal divisor, decimal dividend)
{
    return dividend / divisor;
}

Now, if divisor is 0, we get that we cannot divide by zero error, which is good.

What I would like to do is check if the divisor is 0, and if so, convert it to 1. Is there a way to do this without having many if statements in my method? I think a lot (if) creates a mess. I know that mathematically this should not be done, but for this I have other functions.

For example:

if(divisor == 0)
{
    divisor = 1;
}
return dividend / divisor;

Can this be done without instructions if()?

+3
source share
4 answers

, . , IIF VB.net

return dividend / ((divisor == 0) ? 1 : divisor);

, () .

+15

?:

return (divisor == 0) ? dividend : dividend / divisor 
+11

, if, .

return dividend / divisor == 0 ? 1 : divisor;
+2
source

You can create your own type and overload the / operator to get the desired behavior if you really want to. Implement implicit conversion operators to avoid type conversion or type conversion.

I do not think this would be a good idea, as it would add some overhead at runtime; with the only advantage you get for some code that (maybe) looks a little cleaner.

0
source

Source: https://habr.com/ru/post/1709208/


All Articles