Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in function for a 3-cased if (less than zero, greater than zero, zero)?

Tags:

c#

math

I would like to ask if there's a built-in C# statement that would allow me to write the following with less lines of code:

float fH = Input.GetAxis("Horizontal"); //doesn't really matter where this comes from, but in this case, it's the user's input on a joystick

if (fH < 0)
{
    fH = -1;
}
else if (fH > 0)
{
    fH = 1;
}
else
{
    //don't change anything
}

As far as I know, I can't use

fH = if(...)

because this would only allow for 2 cases while I need 3 cases (smaller than 0, bigger than 0 or 0).

like image 272
tmighty Avatar asked Dec 06 '25 23:12

tmighty


1 Answers

Math.Sign will return whether the input is positive, negative, or 0 with only a single statement (no real need for the if at all).

Math.Sign(-2) 
-1
Math.Sign(-3.3)
-1
Math.Sign(3)
1
Math.Sign(0)
0

It returns an int32, which you can reassign back to your float as you were doing.

fH = Math.Sign(fH);

like image 63
jonsca Avatar answered Dec 08 '25 15:12

jonsca



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!