我是一名新的java程序员,我正在尝试编写一个程序,通过在此类中实现roots()方法来查找二次方程的根。
我想我已经弄清楚如何实现这个方程,但返回语句显示:错误类型不匹配:无法从 double 转换为 Set
如何修复此错误?
谢谢!
package warmup;
import java.util.Set;
public class Quadratic {
/**
* Find the integer roots of a quadratic equation, ax^2 + bx + c = 0.
* @param a coefficient of x^2
* @param b coefficient of x
* @param c constant term. Requires that a, b, and c are not ALL zero.
* @return all integers x such that ax^2 + bx + c = 0.
*/
public static Set<Integer> roots(int a, int b, int c) {
//my code so far
double q = -b + (Math.sqrt(Math.pow(b, 2)-4*a*c)/2*a);
return q;
}
/**
* Main function of program.
* @param args command-line arguments
*/
public static void main(String[] args) {
System.out.println("For the equation x^2 - 4x + 3 = 0, the possible solutions are:");
Set<Integer> result = roots(1, -4, 3);
System.out.println(result);
}
}
最佳答案
以下代码包含对问题中代码的一些修复,请参阅代码中的注释以获取进一步说明:
public static Set<Double> roots(int a, int b, int c) {
Double x = Math.sqrt(Math.pow(b, 2) - 4 * a * c);
Set<Double> result = new HashSet<>(); // return a set that contains the results
result.add((-b + x)/ 2 * a); // -b should be divided by 2a as well
result.add((-b - x)/ 2 * a); // -b should be divided by 2a as well
return result;
}
public static void main(String[] args) {
System.out.println("For the equation x^2 - 4x + 3 = 0, the possible solutions are:");
Set<Double> result = roots(1, -4, 3); // the returned type is Set<Double> not Set<Integer>
System.out.println(result);
}
输出
For the equation x^2 - 4x + 3 = 0, the possible solutions are:
[1.0, 3.0]
关于java - java中带参数的方法的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40394745/