1

当我尝试为二次公式创建方法时,它不会给我任何输出,而且我一直在丢失精度错误。我目前需要任何帮助,因为我似乎无法弄清楚。这是我的代码:

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.
4

2 回答 2

1

当您使用双打进行数学运算时,您正试图返回一个“int”。这就是为什么你正在失去精确度。

于 2013-11-10T17:21:11.247 回答
0

你的方法应该返回一个double. 并将您int的 s 十进制数字设为 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);
}
于 2013-11-10T17:21:47.717 回答