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

You are trying to return an "int" when you are doing mathematical operations with doubles. This is why you are losing precision.

于 2013-11-10T17:21:11.247 に答える
0

メソッドは を返す必要がありますdouble。また、int10 進数を 4 ではなく 4.0 のようにします。これにより、精度が向上します。

編集:メソッドを呼び出す

からメソッドを呼び出そうとしているので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 に答える