java - java中带参数的方法的实现

标签 java

我是一名新的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/

相关文章:

java - 将用户输入的字符拆分为 ArrayList

java - 是否每次执行 java 命令都会启动一个单独的 JVM?

java - 如何只打印出 java 中有 5 个元素的数组的前 3 个元素?

java - 如何使用 hibernate 标准对子对象应用 DISTINCT

java - Android - 仅在具有 MapView 的单个 Activity 上出现许多 OutOfMemoryError 异常

java - Activity和View之间的接口(interface)实现错误

C 中的 Java 实现(可能特定于平台)

java - 使用人工数据设置和播种数据库以进行集成测试的正确方法是什么

c# - 在类似 StringBuilder 的 C 模块中增加多少缓冲区?

java - 线性化数值序列的数学方程