简体   繁体   English

如果我不知道变量是正/负,如何在不调用函数或不使用if的情况下使其变为正数?

[英]If I don't know if a variable is positive/negative, how do I make it positive without calling a function or using if?

This is the code (Java): 这是代码(Java):

    float yd = waypointY - currentY;
    if (yd < 0) {
        yd = yd*(-1);
    }

I don't think this is the best way to do it, and have searched but only found results for when you already know if it's positive or negative. 我认为这不是最好的方法,它已经搜索过,但只有在您知道它是肯定的还是否定的时才找到结果。 I never know if waypointY is more or less than currentY. 我永远不知道waypointY是大于还是小于currentY。

if you use java , there is an API you can use, Math.abs(xy) it will return the absolute value of xy and the source code of abs API as below: 如果使用java ,则有一个可以使用的API Math.abs(xy) ,它将返回xy绝对值abs API源代码,如下所示:

public static float abs(float a) {
    return (a <= 0.0F) ? 0.0F - a : a;
}

AFAIK, this is impossible without if. AFAIK,如果没有,这是不可能的。 Or some variation of. 或一些变化。 Maybe get the sign bit and multiply by something and add something and do something? 也许得到符号位并乘以某物并添加某物并做某事? This seems way too complex, any particular reason not to use if? 这似乎太复杂了,如果不使用任何特殊原因?

Edit: you could use a ternary (or whatever it's called) expression: 编辑:您可以使用三元(或任何称为)表达式:

x = y < 0 ? -y : y;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM