[英]quadratic equations solver in one variable in java
我有这段代码可以解决二阶方程。 用户输入名称与[a-zA-Z]匹配的任何变量的方程,但是程序存在一个问题:如果用户输入的方程中包含多个变量,例如“ x ^ 2 + 2y-20 = 0”(包含两个变量x和y),它将仍然“解决”它并返回“ a = 1,b = 2,c = -20”。
我想让它要求用户仅输入一个变量,例如“ x ^ 2 + 2x-20 = 0”或“ y ^ 2 + 2y-20 = 0”(或任何其他字母,只要相同的字母在整个等式中使用“”表示,也可以解决为“ a = 1,b = 2,c = -20”。
由于该程序当前无法区分变量,因此它会解决具有多个变量的方程式,就好像它们是同一变量(字符)一样,这是错误的。
public class ParseEquation {
public static String coeff(String str, String regex) {
Pattern patt = Pattern.compile(regex);
Matcher match = patt.matcher(str);
// missing coefficient default
String coeff = "+0";
double value = 0;
if(match.find())
coeff = match.group(1);
// always have sign, handle implicit 1
value= Double.parseDouble((coeff.length() == 1) ? coeff + "1"
: coeff);
}
public static String[] quadParse(String arg) {
String str = ("+" + arg).replaceAll("\\s", "");
double a1 = Double.parseDouble(coeff(str, "([+-][0-9]*)([a-z A-Z]\\^2)"));
double b1 = Double.parseDouble(coeff(str, "([+-][0-9]*)([a-z A-Z](?!\\^))"));
double c1= Double.parseDouble(coeff(str, "([+-][0-9]+)(?![a-z A-Z])"));
System.out.println("Values are a: " + a1 + " b: " + b1 + " c: " + c1);
double dis = (Math.pow(b1, 2.0)) - (4 * a1 * c1);
double d = Math.sqrt(dis);
double X = 0, Y = 0;
if (dis > 0.0 || dis < 0.0) {
X = (-b1 + d) / (2.0 * a1);
Y = (-b1 - d) / (2.0 * a1);
String root1 = Double.toString(X);
String root2 = Double.toString(Y);
return new String[]{root1, root2};
} else if (dis == 0.0) {
X = (-b1 + 0.0) / (2.0 * a1);//repeated root
String root2 = Double.toString(X);
return new String[]{root2};
}
return new String[-1];
}
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader (new InputStreamReader(System.in));
String s;
while ((s=r.readLine()) != null) {
String[] pieces = quadParse(s);
System.out.println(Arrays.toString(pieces));
}
}
}
当前,以上代码针对“ x ^ 2 + 2y-20 = 0”返回此错误结果:
Values are a: 1.0 b: 2.0 c: -20.0
[3.58257569495584, -5.58257569495584]
正确的结果是允许用户在方程式中仅输入一个变量字符,例如“ x ^ 2 + 2x-20 = 0”,否则抛出异常。
通过quadParse(s);
将行解析为公式之前quadParse(s);
,检查它的内容。 创建一个长度为26的布尔数组,其中每个索引代表您在方程式中看到的变量。 一次遍历输入的一个字母,如果看到特定的变量,则更新数组。 如果在该过程结束时看到了多个变量,则可以在调用quadParse
之前引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.