KnowledgeBoat Logo

Computer Applications

Sam executes the following program segment and the answer displayed is zero irrespective of any non zero values are given. Name the error. How the program can be modified to get the correct answer?

void triangle(double b, double h)
{	
    double a; 
    a = 1/2 * b * h;
    System.out.println("Area=" + a);	
}	

Input in Java

ICSE Sp 2024

84 Likes

Answer

Logical error.

Modified program:

void triangle(double b, double h)
{	
    double a; 
    a = 1.0/2 * b * h;
    System.out.println("Area=" + a);	
}	
Explanation

The statement is evaluated as follows:

a = 1/2 * b * h;
a = 0 * b * h; (1/2 being integer division gives the result as 0)
a = 0 (Since anything multiplied by 0 will be 0)

To avoid this error, we can replace '1/2' with '1.0/2'. Now the expression will be evaluated as follows:

a = 1.0/2 * b * h;
a = 0.5 * b * h; (The floating-point division will result in result as as 0.5)

This will give the correct result for the given code.

Answered By

35 Likes


Related Questions