+ 1
Hello I have a little problem why is the value of x 2 after this code Int x = 4; Int y = 9; x =(y%x !=0) ? y/x : y;
Question about ?
8 odpowiedzi
+ 3
Answer is 2
0
It says there:
when you divide 9 by 4, is the remainder not equal to 0?
if yes, change the value of x to 9/4 (meaning, 2)
if no, change the value of x to 9.
0
Ok thank you i understood now
🙂
0
? : are called Ternary Operators.
and that ? literally means "Asking a Question"
0
dd
dd
dd
dd
dd
dd
dd
dd
dd
dd
dd
nwes
news
news
news
news
news
news
news
- 1
i dont know what most of that is, but ints cannot by converted to floats like that, so 9/4 = 2, as it rounds down.
- 1
Int x = 4; int y = 9; x = (y%x! = 0) ? Y/x: y;
stands, it might not compile (depending on language), because Y and y are different variables if the language is case-sensitive and Y was not declared yet. (Int and int are also different types.)
Let this compilation problem be resolved, which yields
int x = 4; int y = 9; x = (y%x != 0) ? y/x: y;
After the first two lines, x equals 4 and y equals 9. Then, the first thing to be evaluated is the parenthetical expression, where the % operator is of higher precedence than the != operator. (A possible reason for this is to allow things like a + b == c * d to parse as might be expected: compute both sides and then compare.)
So, y % x equals 9 % 4, which equals 1, and 1 != 0 is true (1 does not equal 0). So, the expression becomes:
x = true ? y/x: y;
The / operator has higher precedence than the ?: operator and the = operator, so y/x evaluates to 9/4, which equals 2, as the / sign is integer division, which leaves:
x = true ? 2: y;
or (since y equals 9)
x = true ? 2: 9;
The ?: operator has higher precedence than the = (assignment) operator, and true?2:9 evaluates to 2 (and false?2:9 would have evaluated to 9).
So 2 gets assigned to x.
- 2
Integers have no decimals, so why do you wait for any?