KnowledgeBoat Logo
|

Computer Applications

A Student executes the given program segment and it results in 1.0, irrespective of the value of n. State the type of the error, write the correct statement:

void solve(int n) 
{ double power=Math.pow(n, 2/3); 
System.out.println(power); 
}

Java Math Lib Methods

2 Likes

Answer

The type of error is logical error.

The correct statement is:

double power = Math.pow(n, 2.0 / 3);

Explanation — In Java, 2/3 uses integer division, which equals 0. So the code computes Math.pow(n, 0), and any number to the power 0 is 1.0, regardless of n. Make the exponent a floating-point value—e.g., 2.0/3 or 2/3.0 or 2.0/3.0—so it evaluates to 0.666… and correctly computes n2/3n^{2/3}.

The corrected code is as follows:

void solve(int n) 
{ double power = Math.pow(n, 2.0 / 3);
System.out.println(power); 
}

Answered By

3 Likes


Related Questions