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 .
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
Give the output of the following program segment:
int x[]={2,45,7,67,12,3}; int i, t=0; for(i=0, t=5;i<3;i++,t--) { System.out.println(x[i]+x[t]); }Write Java statements for the following:
(a) Initialise the array with the three favourite subjects.
(b) Declare an array to store the marks in 3 subjects of 40 students.Consider the following program segment and answer the questions given:
for(int k=1;k<=5;k++) System.out.println(k); System.out.println(k);(a) Will the program segment get executed successfully?
(b) If not, state the type of error?
(c) How do you correct the program if it has any error?Consider the array:
int a[]={12, 35, 40, 22, 56, 9, 70};(a) In the above given array, using linear search, how many iterations are required to check for the existence of the value 56?
(b) If the array is arranged in descending order, how many iterations are required to check for the existence of 56 using linear search?