Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting lowest number from several numbers

I have two numbers. I want the lower number to be the subtracted from both values.

x: 1000
y: 200
=> result: x = 800 and y = 0.

The following is kinda ugly to me, so is there a better approach I could do this?

if (x <= y) {
    y = y - x;
    x = 0
} else {
    x = x - y;
    y = 0;
}
like image 871
membersound Avatar asked Oct 23 '12 10:10

membersound


People also ask

How do you subtract a number from multiple cells?

To subtract a number from a range of cells, click on the cell where you want to display the result, and enter “=” (equal) and the cell reference of the first number then “-” (minus) and the number you want to subtract. You can then copy this formula down the column to the rows below.

How do you subtract numbers when the top number is smaller?

To subtract whole numbers we write them as in an addition problem and subtract each digit moving from the right to the left. If when subtracting digits, the top number is smaller than the bottom, borrowing becomes necessary. We borrow one from the digit to the left. - 9 We have written 41 as 30 + 11.


2 Answers

This should do it:

int min = Math.min(x, y);
x -= min;
y -= min;
like image 132
Duncan Jones Avatar answered Sep 17 '22 22:09

Duncan Jones


You can do following:

x = x - y;
y = 0;

if(x<0)
{
    y = -x
    x = 0;
}
like image 28
Azodious Avatar answered Sep 19 '22 22:09

Azodious