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

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

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

问题

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

  1. public class Abs {
  2. public static int abs(int x) {
  3. if (x < 0) { return -x; }
  4. if (x >= 0) { return x; }
  5. assert false;
  6. return 0;
  7. }
  8. }
英文:

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

  1. public class Abs {
  2. public static int abs(int x) {
  3. if(x &lt; 0) { return -x; }
  4. if(x &gt;= 0) { return x; }
  5. assert false;
  6. return 0;
  7. }
  8. }

答案1

得分: 1

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

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

或者放入一个方法中:

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

"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:

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

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

答案2

得分: 0

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

  1. public class Abs {
  2. public static int abs(int x) {
  3. return x < 0 ? -x : x;
  4. }
  5. }
英文:

You can use the ternary operator to simplify the code

  1. public class Abs {
  2. public static int abs(int x) {
  3. return x &lt; 0 ? -x : x;
  4. }
  5. }

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:

确定