-3

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.

4

3 回答 3

4

更改powMath.pow。类Math是一个static类,需要从类本身获取方法。

于 2012-11-04T06:21:48.067 回答
1

Math.用作函数的前缀,pow因为pow(double a, double b)它是类中static的方法java.lang.Math

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);
}

另外我认为您可能希望sqrt从此方法返回,因此将返回类型从voidto更改为double并在最后添加一个 return 语句,如下所示:

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;
}
于 2012-11-04T06:22:37.317 回答
1

Math.pow 是一个使用起来相对昂贵的操作,而且在许多情况下打字时间也更长,所以如果可以的话,我会避免使用它。使用起来更简单(对您和计算机来说更快)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));
}

印刷

[-2.0, -1.0]
[-1.0, 1.0]
[-2.0]
[]

请注意,您可以没有,一两个真正的解决方案。

于 2012-11-04T08:43:10.527 回答