我想制作一个二次方公式程序。我成功完成了基础知识但有两个主要错误。一个当我尝试输入十进制值作为a,b或c时,另一个当我必须处理i(虚数)时。我该如何解决这些问题?我也很感谢在这里简化代码的方法是我的代码:
import java.util.Scanner;
public class Calculator {
public static void main (String args[]){
System.out.println("Input a");
Scanner ai = new Scanner(System.in);
double a = ai.nextInt();
System.out.println("Input b");
Scanner bi = new Scanner(System.in);
double b = bi.nextInt();
System.out.println("Input c");
Scanner ci = new Scanner(System.in);
double c = ci.nextInt();
double Square1 = Math.pow(b, 2);
double Square2 = -4*a*c;
double Square3 = Square1 + Square2;
double Square = Math.sqrt(Square3);
double Bottom = 2*a;
double Top1 = -b + Square;
double x1 = Top1/Bottom;
double Top2 = -b - Square;
double x2 = Top2/Bottom;
System.out.printf("X = %s", x1);
System.out.printf("X = %s", x2);
}
}
答案 0 :(得分:1)
你得到的第一个错误是因为你使用了方法nextInt()。当您尝试读取double - Method nextInt
时,它会抛出InputMismatchException而不是nextInt()你应该使用方法nextDouble。
第二个错误:Java不支持虚数:(
如果你想使用虚数,你必须写你的类ImaginaryNumber。
这是您重构的代码:
import java.util.Scanner;
public class Calculator {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Input a");
double a = input.nextDouble();
System.out.println("Input b");
double b = input.nextDouble();
System.out.println("Input c");
double c = input.nextDouble();
double square1 = Math.pow(b, 2);
double square2 = -4 * a * c;
double square3 = square1 + square2;
if (square3 < 0) {
double square = Math.sqrt(square3);
double bottom = 2 * a;
double top1 = -b + square;
double x1 = top1 / bottom;
double top2 = -b - square;
double x2 = top2 / bottom;
System.out.printf("X = %s", x1);
System.out.println();
System.out.printf("X = %s", x2);
} else {
System.out
.println("Can not calculate square root for negative number");
}
input.close();
}
}
你可以注意到我添加了
if (square3 < 0) {
这是因为方法Math.square只能采取正面。 如果您传递负数,它将返回NaN - 不是数字: Math.sqrt