二次公式的方法不会给出输出和错误

时间:2013-11-10 17:17:35

标签: java methods return

当我尝试为二次公式制作方法时,它不会给我任何输出,所以我一直迷失精度错误。我目前需要任何帮助,因为我似乎无法弄明白。这是我的代码:

import java.util.Scanner;

public class HelperMethod {

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Pick an option:");
    System.out.println("Option 1: Quadratic Formula");
    System.out.println("Option 2: Newtons Method");
    System.out.println("Option 3: ISBN checker");
    int option = keyboard.nextInt();

    if(option == 1){
        System.out.print("Please enter an 'a' value:");
        double a = keyboard.nextDouble();
        System.out.print("Please enter a 'b' value:");
        double b = keyboard.nextDouble();
        System.out.println("Please enter 'c' value:");
        double c = keyboard.nextDouble();
    }
}
public int quadraticFormula(double a, double b, double c, boolean returnSecond){
    return (-b + Math.sqrt(b * b - 4.0 * a * c))/(2.0 * a);
}
}

输出:没有给我一个问题的答案

Pick an option:
Option 1: Quadratic Formula
Option 2: Newtons Method
Option 3: ISBN checker
1
Please enter an 'a' value:2
Please enter a 'b' value:3
Please enter 'c' value:
4

Process completed.

2 个答案:

答案 0 :(得分:0)

当你用双打进行数学运算时,你试图返回一个“int”。这就是你失去精确度的原因。

答案 1 :(得分:0)

你的方法应该返回double。并使你的int十进制数字像4.0而不是4.这将有助于精确。

编辑:通话方法

由于您尝试从main调用该方法,因此您必须将其设为静态

public static int quadraticFormula(double a, double b, double c, boolean returnSecond){
    return (-b + Math.sqrt(b * b - 4.0 * a * c))/(2.0 * a);
}

然后确保从main调用它以获得输出

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Pick an option:");
    System.out.println("Option 1: Quadratic Formula");
    System.out.println("Option 2: Newtons Method");
    System.out.println("Option 3: ISBN checker");
    int option = keyboard.nextInt();

    if(option == 1){
        System.out.print("Please enter an 'a' value:");
        double a = keyboard.nextDouble();
        System.out.print("Please enter a 'b' value:");
        double b = keyboard.nextDouble();
        System.out.println("Please enter 'c' value:");
        double c = keyboard.nextDouble();
    }

    System.out.println(quadraticFormula(a, b, c));
}

编辑:方法返回void

public static void quadraticFormula(double a, double b, double c){
    double quad = -b + Math.sqrt(b * b - 4.0 * a * c))/(2.0 * a)
    System.out.println(quad);
}

public static void main(String[] args){
    quadraticFormula(a, b, c);
}