3

我正在做一个学校作业。我应该实现一个类并提供方法 getSolution1 和 getSolution2。但是,我的代码有两个我无法弄清楚的问题。

问题 #1 在这一行:

solution1= ((-1*b)/> + Math.sqrt(Math.pow(b,2)-(4*a*c)));

编译器告诉我:标记“>”上的语法错误,删除此标记。我不知道我的语法是否做错了。

问题 #2 在输出线上:

String quadEquation= "The quadratic equation is "+ a + Math.pow(("x"),2) + " + " + b+"x"+ " + " + c+ " =0";

在 Math.pow 下我收到一条错误消息: Method pow is not applicable for the arguments String

这是我的整个代码:

       public class QuadraticEquation

{

  double a;
  double b;
  double c;
  double solution1;
  double solution2;

QuadraticEquation (double a, double b, double c){

     a= this.a;
     b= this.b;
     c= this.c;
}

public boolean hasSolution (){

  if ((Math.pow(b,2))- (4*a*c)<0){

    return false;
  }

  else

  {
    return true;
  }
}

 public double getSolution1 (double a, double b, double c)

{

  if (hasSolution){

      solution1= ((-1*b) + Math.sqrt(Math.pow(b,2)-(4*a*c))) / 2*a;

    return solution1;

  }

}

 public double getSolution2 (double a, double b, double c){

    if (hasSolution){

        solution1= ((-1*b) - Math.sqrt(Math.pow(b,2)-(4*a*c))) / 2*a;
    return solution2;
}

}

public String toString (double a, double b, double c){

    String quadEquation= "The quadratic equation is "+ a + "x^2" + " + " + b+"x"+ " + " + c+ " =0";

    return quadEquation;

  }

}

由于这是一项学校作业,因此我正在寻找解决此问题的指导。

谢谢你。

4

2 回答 2

8

您的第一个问题是您不能一起使用 /> 。这不是正确的操作。 http://docs.oracle.com/javase/tutorial/java/nutsandbolts/opsummary.html

第二个问题是因为 Math.pow 需要两个数字。你有一个字符串在那里。这就像试图获得苹果这个词的力量。你做不到。您必须首先将该字符串转换为 int。如何在 Java 中将 String 转换为 int?

于 2013-07-19T19:13:19.557 回答
2
solution1= ((-1*b) + Math.sqrt(Math.pow(b,2)-(4*a*c))) / 2*a;

/>Java中没有a这样的东西。

String quadEquation= "The quadratic equation is "+ a + "x^2" + " + " + b+"x"+ " + " + c+ " =0";

当您传递字符串“x”时,Math.pow 需要数字。符号“^”通常用于表示 的幂,因此 x^2 是 x 的 2 的幂。我认为在标准输出中写上标没有简单的解决方案。

如果方程无解,Java 无法理解返回什么

public double getSolution2 (double a, double b, double c){

    if (hasSolution){
        solution1= ((-1*b) - Math.sqrt(Math.pow(b,2)-(4*a*c))) / 2*a;
        return solution2;
    }
    return -1; // or throw an exception.
}

返回 -1 将修复它。

于 2013-07-19T19:37:19.050 回答