有简化这段代码的方法吗?该代码的目标是在给定整数后返回绝对值。

huangapple go评论57阅读模式
英文:

Is there a way to simplify this code which aims to return an absolute value given an integer?

问题

以下是翻译好的代码部分:

public class Abs {
    public static int abs(int x) {
        if (x < 0) { return -x; }
        if (x >= 0) { return x; }
        assert false;
        return 0;
    }
}
英文:

Is there a way to simplify this piece of code further? The codes aim is to return an absolute value given an integer.

public class Abs {
public static int abs(int x) {
if(x &lt; 0) { return -x; }
if(x &gt;= 0) { return x; }
assert false;
return 0;
}
}

答案1

得分: 1

你可以将这部分代码放入一个整数中,并在赋值时检查条件。

int y = x < 0 ? -x : x;

或者放入一个方法中:

public static int abs(int x) {
    return x < 0 ? -x : x;
}

"assert false" 的部分永远不会被执行到,因此是无用的。

英文:

You could put this in an integer and check the condition when you assign a value.
int y = x &lt; 0 ? -x : x;
Or in a method:

public static int abs(int x) {
return x &lt; 0 ? -x : x;
}

The "assert false" will never be reached, so it is useless.

答案2

得分: 0

你可以使用三元运算符来简化代码

public class Abs {
   public static int abs(int x) {
     return x < 0 ? -x : x;
   }
}
英文:

You can use the ternary operator to simplify the code

public class Abs {
   public static int abs(int x) {
     return x &lt; 0 ? -x : x;
   }
}

huangapple
  • 本文由 发表于 2020年8月27日 13:07:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63609551.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定