这道题是班里同学的做法
题目是一元二次方程
package bad;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Equation {
public static Map<String,Double> Unary(double a,double b,double c) {
Map<String, Double> map = new HashMap<String, Double>();
double delta = b * b - 4 * a * c;
map.put(“delta”, delta);
if (delta >= 0) {
double x1 = ((-b + Math.sqrt(delta)) / (2 * a));
double x2 = ((-b - Math.sqrt(delta)) / (2 * a));
map.put(“x1”, x1);
map.put(“x2”, x2);
} else {
double realN = -b * b / (2 * a);
double imaginary = Math.sqrt(-delta) / (2 * a);
map.put(“realN”, realN);
map.put(“imaginary”, imaginary);
}
return map;
}
public static void main(String[] args){
Scanner in=new Scanner(System.in);
System.out.println(“请输入a,b,c的值”);
double a=in.nextInt();
double b=in.nextInt();
double c=in.nextInt();
Map<String,Double> map=Equation.Unary(a,b,c);
if(map.get(“delta”)>=0){
System.out.println(“解出x1为”+map.get(“x1”));
System.out.println(“解出x2为”+map.get(“x2”));
}else{
System.out.println(“此方程有虚解”);
System.out.println(“实数为”+map.get(“realN”));
System.out.println(“虚数为”+map.get(“imaginary”));
}
}
}
老师的代码
public class SolveEquation {
public static boolean isZero(double a) {
return Math.abs(a) < 1e-6;
// return false;
}
public static double[] solveUnaryQuadraticEquation(double a, double b, double c) {
double[] result = { 0.0, 0.0,2.0 };//result[2]用于对解的性质做描述
double delta = b * b - 4 * a * c;
if (isZero(a)) {
result[2] = 0;//不是二次方程
}
else if(delta<0) {
result[2]=1;//没有实数解
}
else {
double tem = Math.sqrt(delta);
result[0] = (-b + tem) / 2.0 / a;
result[1] = (-b - tem) / 2.0 / a;
}
return result;
}
}
public class tester {
public static void main(String[] args) {
// TODO Auto-generated method stub
double[] r = SolveEquation.solveUnaryQuadraticEquation(1.0, 0, 0);
if (SolveEquation.isZero(r[2]))
System.out.println(“二次项系数不能为0”);
else if (SolveEquation.isZero(r[2] - 1))
System.out.println(“没有实数解!”);
else {
System.out.println("x1= " + r[0]);
System.out.println("x2= " + r[1]);
}
}
}
说实话老师这种做法真的看不懂 呜呜呜
老师还嫌弃我们的代码很菜 呜呜呜