92.3k views
4 votes
Consider the following code segment, which is intended to display 0.5.

int num1 = 5;
int num2 = 10;
double ans = num1 / num2;
System.out.print(ans);
Which of the following best describes the error, if any, in the code segment?
A. There is no error and the code works as intended.
B. The code should have cast the expression num1 / num2 to double.
C. The code should have cast either num1 or num2 in the expression num1 / num2 to double.
D. The code should have declared ans as an int.
E. The code should have initialized num1 to 5.0 and num2 to 10.0.

User Jan Kuri
by
7.4k points

1 Answer

4 votes

Final answer:

The error in the code segment is that the division of num1 / num2 will result in an integer division. To fix this, cast either num1 or num2 to double before performing the division.

Step-by-step explanation:

The error in the code segment is that the division of num1 / num2 will result in an integer division because both num1 and num2 are of type int. Integer division truncates any decimal places, so the result will be 0 instead of 0.5. To fix this, we should cast either num1 or num2 to double before performing the division. The correct code should be:

int num1 = 5; int num2 = 10; double ans = (double)num1 / num2; System.out.print(ans);

User Beniaminus
by
7.6k points