//主要的思路是,遍历二次式字符串,计算常数项、一次项、二次项的系数和,再利用求根公式得出答案 #include <iostream> #include <string> #include <cmath> #include <cstdio> using namespace std; int main() { string str, str2; cin >> str; string left = str.substr(0, str.find('=')), right = str.substr(str.find('=') + 1); for (int i = 0; i < right.length(); i++) { //右侧表达式异号 if (right[i] == '+') right[i] = '-'; else if (right[i] == '-') right[i] = '+'; } str2 = left + '-' + right + "!!"; //式子归于左边 //cout<<str2<<endl;//查看整理后的式子 int a = 0, b = 0, c = 0; for (int i = 0; i < str2.length() - 2; i++) { if (str2[i] <= '9' && str2[i] >= '0') { if (str2[i + 1] == '+' || str2[i + 1] == '-' || str2[i + 1] == '!') { //常数 if (i == 0) { //首项的情况 c = c + str2[i] - '0'; } else { //非首项的情况 if (str2[i - 1] == '+') c = c + str2[i] - '0'; if (str2[i - 1] == '-') c = c - str2[i] + '0'; } } else if (str2[i + 1] == 'x' && str2[i + 2] != '^') { //一次项系数 if (i == 0) { //首项的情况 b = b + str2[i] - '0'; } else { //非首项的情况 if (str2[i - 1] == '+') b = b + str2[i] - '0'; if (str2[i - 1] == '-') b = b - str2[i] + '0'; } } else if (str2[i + 1] == 'x' && str2[i + 2] == '^') { //二次项系数 if (i == 0) { //首项的情况 a = a + str2[i] - '0'; } else { //非首项的情况 if (str2[i - 1] == '+') a = a + str2[i] - '0'; if (str2[i - 1] == '-') a = a - str2[i] + '0'; } } } else if (str2[i] == 'x') { if (i == 0) { //首项的情况 if (str2[i + 1] != '^') { //一次项x b++; } else if (str2[i + 1] == '^') { a++; } } else { //非首项的情况 if (str2[i - 1] <= '9' && str2[i - 1] >= '0') continue; //常数已判断过 else if (str2[i - 1] == '+') { if (str2[i + 1] != '^') { //一次项x b++; } else if (str2[i + 1] == '^') { //二次项x a++; } } else if (str2[i - 1] == '-') { if (str2[i + 1] != '^') { //一次项x b--; } else if (str2[i + 1] == '^') { //二次项x a--; } } } } } //cout << "a:" << a << " " << "b:" << b << " " << "c:" << c;//查看各项系数和 if(pow(b, 2) - 4 * a * c<0){ printf("No Solution");//无解 return 0; } double answer1 = (-b + pow(pow(b, 2) - 4 * a * c, 0.5)) / (2 * a), answer2 = (-b - pow(pow(b, 2) - 4 * a * c, 0.5)) / (2 * a); printf("%.2f", min(answer1, answer2)); printf(" "); printf("%.2f", max(answer1, answer2)); return 0; }