Expressions and Assignment Statements

AP Computer Science A· difficulty 2/5

public static double half(int n) {
    return n / 2;
}

What is wrong with this method?

  • A

    Division by 2 is undefined for negatives

  • B

    Integer division truncates; cast at least one operand to double

    check_circle
  • C

    The return type should be int

  • D

    Nothing is wrong

Explanation

n / 2 performs integer division because both operands are int, so half(3) returns 1.0. Use (double) n / 2 or n / 2.0 to retain the fractional part.

Want 10 more like this — adaptive to your weak spots?

Related questions