public class EquationReducer {
public static final String DIGITAL="-?\\d+\\.?\\d*";
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String equation=scan.next();
System.out.println(Arrays.toString(reduce(equation)));
scan.close();
}
public static double[] reduce(String equation){
if(equation.matches(DIGITAL
+ "x"
+ "\\+"
+ DIGITAL
+ "="
+ DIGITAL)){
double[] args=new double[3];
String[] parts=equation.split("x\\+");
args[0]=Double.parseDouble(parts[0]);
args[1]=Double.parseDouble(parts[1].split("=")[0]);
args[2]=Double.parseDouble(parts[1].split("=")[1]);
if(args[0]!=0.0){
System.out.println(Arrays.toString(args));
double solution=(args[2]-args[1])/args[0];
return new double[]{solution};
}
return null;
}
if(equation.matches(DIGITAL+
"x\\^2"+
"\\+"+
DIGITAL+
"x"+
"\\+"+
DIGITAL+
"="+
DIGITAL)){
double[] args=new double[4];
String[] firstSplitParts=equation.split("x\\^2\\+");
args[0]=Double.parseDouble(firstSplitParts[0]);
String[] secondSplitParts=firstSplitParts[1].split("x\\+");
args[1]=Double.parseDouble(secondSplitParts[0]);
args[2]=Double.parseDouble(secondSplitParts[1].split("=")[0]);
args[3]=Double.parseDouble(secondSplitParts[1].split("=")[1]);
System.out.println(Arrays.toString(args));
double delt=Math.sqrt((Math.pow(args[2],2.0)-4*args[0]*(args[2]-args[3])));
if(delt>0){
double solution1=(-args[1]+delt)/2*args[0];
double solution2=(-args[2]-delt)/2*args[0];
return new double[]{solution1,solution2};
}else{
System.out.println("无解!");
return null;
}
}
return null;
}
}
|