Change pow
to Math.pow
. The Math
class is a static
class, and you need to get the method from the class itself.
using math class in java [closed]
Question
I'm trying to calculate the power of a double
to calculate the Quadratic Formula
Here is the code:
private Scanner sc;
double a, b, c;
// Input Coefficients
public void InputCoeff() {
sc = new Scanner(System.in);
System.out.println("Please enter the coefficients of this quadratic equation.");
System.out.println("'ax2 + bx + c = 0'");
System.out.print("a = ");
a = sc.nextDouble();
if(a == 0){
System.out.println("Coefficient of x2 ('a') can't be zero.");
System.out.println("Otherwise, it'll be a linear funciton.");
}
System.out.print("b = ");
b = sc.nextDouble();
System.out.print("c = ");
c = sc.nextDouble();
}
public void SqRt(double x, double y, double z) {
double sqrt;
sqrt = pow(y, 2) - (4 * x * z); // This generates an error
System.out.println();
}
Why this error?
Thanks.
Solution
OTHER TIPS
Use Math.
as prefix to your function pow
because pow(double a, double b)
is an static
method from java.lang.Math
class:
public void SqRt(double x, double y, double z) {
double sqrt;
sqrt = Math.pow(y, 2) - (4 * x * z); // This generates an error
System.out.println(sqrt);
}
Also I think you may want to return sqrt
from this method so change the return type from void
to double
and add a return statement in the end as below:
public dobule SqRt(double x, double y, double z) {
double sqrt;
sqrt = Math.pow(y, 2) - (4 * x * z); // This generates an error
System.out.println(sqrt);
return sqrt;
}
Math.pow is a relative expensive operation to use and also longer to type in many case so I would avoid it if you can. It's much simpler (and faster for you and the computer) use x * x
public static Set<Double> solve(double a, double b, double c) {
Set<Double> solutions = new TreeSet<Double>();
double discriminant = b * b - 4 * a * c;
solutions.add((-b - Math.sqrt(discriminant)) / (2 * a));
solutions.add((-b + Math.sqrt(discriminant)) / (2 * a));
solutions.remove(Double.NaN);
return solutions;
}
public static void main(String... args) {
System.out.println(solve(1, 3, 2));
System.out.println(solve(1, 0, -1));
System.out.println(solve(1, 4, 4));
System.out.println(solve(1, 0, 1));
}
prints
[-2.0, -1.0]
[-1.0, 1.0]
[-2.0]
[]
Note that you can have none, one or two real solutions.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow