我怎样才能从二次公式中得到一个例外?

How can I get an exception from a quadratic formula?

package com.mycompany.mavenproject1;

import java.util.Scanner;

public class Mavenproject1 {

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        double a, b, c;
        double x1, x2;
        System.out.println("Ingresa el valor de a: ");
        a = sc.nextDouble();
        System.out.println("Ingresa el valor de b: ");
        b = sc.nextDouble();
        System.out.println("Ingresa el valor de c: ");
        c = sc.nextDouble();

        try {
            x1 = ((-b) - (Math.sqrt(Math.pow(b, 2) - 4 * a * c))) / 2 * a;
            x2 = ((-b) + (Math.sqrt(Math.pow(b, 2) - 4 * a * c))) / 2 * a;
            System.out.println("x1: " + x1 + ", x2: " + x2);
        } catch (Exception e) {
            System.out.println("Hay un problema");
        }

    }
}

B 是从 answer 求平方根的值,然后你想抛出异常。

例子:√0^2 = 0,那么是不可整除的。

解决方案:

use If-else statement and throw exceptions(custom or default).

//如果平方根B为0,则抛出错误

try {
    if(b == 0){
        throw new Exception();
    }
    else {
    x1 = ((-b) - (Math.sqrt(Math.pow(b, 2) - 4 * a * c))) / 2 * a;
    x2 = ((-b) + (Math.sqrt(Math.pow(b, 2) - 4 * a * c))) / 2 * a;
    System.out.println("x1: " + x1 + ", x2: " + x2);
    }

    } catch (Exception e) {
        System.out.println("There is A Problem");
    }

我复制了它,这是给你的奖励: https://onlinegdb.com/9oqNMLySU

Give a thumbs up if it helps. Gladge

具有 double 值的算术不会抛出异常。也不会取零或负数的平方根。因此,您的代码将必须测试特定输入(或结果)并显式抛出异常。

提示:

  • 阅读 Math.sqrt(double)Double.isNaN(double)

    的 javadoc
  • 了解 NaN 在浮点运算中的含义,

  • 阅读有关 √-1 和复数的知识(如果您忘记了 high-school 数学 类),

  • 做一些代数来找出是什么值导致二次公式产生复数作为“根”。

public static void main(String[] args) throws Exception {
    Scanner sc = new Scanner(System.in);
    int a, b, c;
    int x1, x2, divisor, dividendo1, dividendo2, raiz, resta, cuadrado;
    System.out.println("Ingresa el valor de a: ");
    a = sc.nextInt();
    System.out.println("Ingresa el valor de b: ");
    b = sc.nextInt();
    System.out.println("Ingresa el valor de c: ");
    c = sc.nextInt();
    cuadrado = b * b;
    resta = cuadrado - 4 * a * c;
    raiz = (int)Math.sqrt(resta);
    if (raiz==0) {
        throw new ArithmeticException();
    }
    dividendo1 = -b - raiz;
    dividendo2 = -b + raiz;
    divisor = 2 * a;
    x1 = dividendo1 / divisor;
    x2 = dividendo2 / divisor;    
    System.out.println("x1: " + x1 + ", x2: " + x2);
    
}

}

我明白了!