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
Evaluate the expression when the value of x = 2:
x = x++ + ++x + x
The following code segment should print "You can go out" if you have done your homework (dh) and cleaned your room (cr). However, the code has errors. Fix the code so that it compiles and runs correctly.
boolean dh = True; boolean cr= true; if (dh && cr) System.out.println("You cannot go out"); else System.out.println("You can go out");
How many times will the following loop execute? What value will be returned?
int x = 2; int y = 50; do{ ++x; y -= x++; } while(x <= 10); return y;
Write the output of the following String methods:
(a) "ARTIFICIAL".indexOf('I')
(b) "DOG and PUPPY".trim().length()