开发者

In java, how would I make a calculation where the greatest number is subtracted by the smaller number?

If I get two totals as an input, whe开发者_如何学Cre the first and second number may vary in which is larger, how would I set the calculation to always be the greater number subtracted by the smaller one?


I would use something like that:

public int sub(int firstNumber, int secondNumber) {
    return Math.max(firstNumber, secondNumber) - Math.min(firstNumber, secondNumber);
}

or:

public int sub(int firstNumber, int secondNumber) {
    return Math.abs(firstNumber - secondNumber);
}


substract both and return the absolute value


You could use the following:

Math.abs(a - b)


       public int sub(int a, int b) {
          if(a > b){
            return a - b;
          }
          else if (b > a) {
            return b - a;
          }
          else return 0;
       }


The Math class provides a few methods that can do that for you, or you can just do a simple swap of values like that:

public int sub(int firstNumber, int secondNumber) {

    if( firstNumber < secondNumber ) {
        int temp = secondNumber;
        secondNumber = firstNumber;
        firstNumber = temp;
    }
    return firstNumber - secondNumber;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜