语法错误";" ,,预期在线"双a,b,c,判别,root;"
如何解决此错误?
public class Quadratic {
double a, b, c, discriminant, root;
discriminant = (b * b) - 4 * a * c;
public Quadratic(double a, double b, double c) {
}
public String calculateroots() {
if (discriminant >= 0){
root = Math.sqrt(discriminant) / (2 * a);
System.out.println("Your roots are " + (-1 * b) + "+" + root + "and" + (-1 * b) + (-1 * root) +".");
}
else {
root = Math.sqrt(Math.abs(discriminant)) / (2 * a);
System.out.println("Your roots are " + (-1 * b) + "+ i" + root + "and" + (-1 * b) + "i" + (-1 * root) +".");
}
}
}
答案 0 :(得分:0)
注意构造函数中的变量初始化为discriminant
中的calculateroots
初始化。
public class Quadratic {
double a, b, c, discriminant, root;
public Quadratic(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public void calculateroots() {
discriminant = (b * b) - 4 * a * c;
if (discriminant >= 0){
root = Math.sqrt(discriminant) / (2 * a);
System.out.println("Your roots are " + (-1 * b) + "+" + root + "and" + (-1 * b) + (-1 * root) +".");
}
else {
root = Math.sqrt(Math.abs(discriminant)) / (2 * a);
System.out.println("Your roots are " + (-1 * b) + "+ i" + root + "and" + (-1 * b) + "i" + (-1 * root) +".");
}
}
}
答案 1 :(得分:-1)
你走了。
public class Quadratic {
double a, b, c, discriminant, root;
public Quadratic(double a, double b, double c) {
discriminant = (b * b) - 4 * a * c;
}
public void calculateroots() {
if (discriminant >= 0) {
root = Math.sqrt(discriminant) / (2 * a);
System.out.println("Your roots are " + (-1 * b) + "+" + root + "and" + (-1 * b) + (-1 * root) + ".");
} else {
root = Math.sqrt(Math.abs(discriminant)) / (2 * a);
System.out.println("Your roots are " + (-1 * b) + "+ i" + root + "and" + (-1 * b) + "i" + (-1 * root) + ".");
}
}
}
答案 2 :(得分:-1)
只回答你的问题......语法错误是由
的位置引起的 discriminant = (b * b) - 4 * a * c;
判别式被赋予(a, b ,c)
未初始化的变量。
我建议将其移至calculateroots()
并将返回类型更改为void:
public class Quadratic {
double a, b, c, discriminant, root;
public Quadratic(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public void calculateroots() {
discriminant = (b * b) - 4 * a * c;
if (discriminant >= 0){
root = Math.sqrt(discriminant) / (2 * a);
System.out.println("Your roots are " + (-1 * b) + "+" + root + "and" + (-1 * b) + (-1 * root) +".");
}
else {
root = Math.sqrt(Math.abs(discriminant)) / (2 * a);
System.out.println("Your roots are " + (-1 * b) + "+ i" + root + "and" + (-1 * b) + "i" + (-1 * root) +".");
}
}
}
这样你只需创建Quadratic实例并为a
,b
和c
的构造函数赋值,然后调用calculateroots()