88.0k views
0 votes
Consider the following code:

int diff = 0;
if (Math.abs(num1 - num2) == (num1 - num2))
{
diff = num1 - num2;
}
else if (Math.abs(num2 - num1) == (num2 - num1))
{
diff = num2 - num1;
}
Which of the following will have the exact same result?

I.

int diff = Math.abs(num1) - num2;
II.

int diff = Math.abs(num1 - num2);
III.

int diff = Math.abs(num2 - num1);
II and III only
I only
I sets diff to the absolute value of num1 minus the value of num2. This could be negative, while in the code segment diff is always positive.
II only
I, II, and III
III only

Consider the following code: int diff = 0; if (Math.abs(num1 - num2) == (num1 - num-example-1
User Tessaract
by
5.7k points

1 Answer

5 votes

Answer:

II & III

this is because the manner of code Math.Abs allows for the if statement to be done by itself when implemented in both of those ways. However with I creates a problem. The ABS function will only apply to num1, and the way you're showing in the if statement doesn't have any manner where only num1 has ABS applied to it.

Step-by-step explanation: