209k views
0 votes
A programmer knows that the value of the area of a triangle is 1/2 times the base times the height, and writes the following code:

int base = 7, height = 15;
double area = (double)((height * base) / 2);
What is wrong with this code?
A) The order of operations is incorrect.
B) It should be base * height, not height * base.
C) You do not need to cast the result to a double because the area will always have an integer value.
D) The cast is applied too late. The integer result will be cast to a double, always ending in .0.

1 Answer

4 votes

Final answer:

The code in the question has an issue with the placement of the cast. By moving the cast before the operation, the code will produce the desired result.

Step-by-step explanation:

The problem with the code is option D) The cast is applied too late. The integer result will be cast to a double, always ending in .0.

The correct code should be:

int base = 7, height = 15; double area = (double)(height * base) / 2;

By placing the cast (double) before the operation, the result of the multiplication will be converted to a double, and then the division by 2 will be performed, resulting in a double value for the area.

User Weather Vane
by
7.5k points