也贴个自己的code, 跟前面一个童鞋说的类似,碰见扩号或者等号就递归,这样子也
很容易扩展到乘号或者除号.
double solve(string str, double x) {
int x_coeff, y_coeff, con;
int size = str.size();
x_coeff = y_coeff = con = 0;
getCoeff(str, 0, x_coeff, y_coeff, con);
if (y_coeff != 0) {
double y = -(con + x_coeff*x) / y_coeff;
return y;
}
else return DBL_MAX;
}
int getCoeff(string &str, int start, int &x_coeff, int &y_coeff, int &con) {
int end;
int num;
int digit_flag = 0;
int sign = 1;
int i;
for (i = start; i < str.size(); i++) {
num = 0;
if (str[i] == ' ') continue;
while (str[i] >= '0' && str[i] <= '9') {
num = num * 10 + str[i] - '0';
i++;
digit_flag = 1;
}
if (digit_flag == 1) {
if (str[i] == 'x') x_coeff += sign * num;
else if (str[i] == 'y') y_coeff += sign * num;
else con += sign * num;
digit_flag = 0;
}
else {
if (str[i] == 'x') x_coeff += sign;
else if (str[i] == 'y') y_coeff += sign;
}
if (str[i] == '+') sign = 1;
else if (str[i] == '-') sign = -1;
if (str[i] == '(') {
int a, b, c;
a = b = c = 0;
i = getCoeff(str, i+1, a, b, c);
x_coeff += sign * a;
y_coeff += sign * b;
con += sign * c;
}
else if (str[i] == '=') {
int a, b, c;
a = b = c = 0;
i = getCoeff(str, i + 1, a, b, c);
x_coeff -= a;
y_coeff -= b;
con -= c;
}
else if (str[i] == ')') return i;
}
return i;
}