目录
一、题目内容
二、输入描述
三、输出描述
四、输入输出示例
五、完整C语言代码
一、题目内容
设计一个二次方程计算器
二、输入描述
每个案例是关于x的一个二次方程表达式,为了简单,每个系数都是整数形式。
三、输出描述
每个案例输出两个实数(由小到大输出,中间由空格隔开),保留两位小数;如果无解,则输出“No Solution”。
四、输入输出示例
输入:
x^2+x=3x+4输出:
-1.24 3.24
五、完整C语言代码
AC代码~#include<stdio.h>
#include<string.h>
#include<math.h>int a, b, c;
void subStr(char* s, char* subs, int a, int b) { // 子串分割函数(将等号左右分成两个表达式)int i = 0;for (int j = a; j <= b; j++) {subs[i] = s[j];i++;}subs[b + 1] = '\0';
}void process(char* s, int mode) { // 处理子串函数int i = 0;int num = 0;int flag = 1;if (mode == 0) { // 左边等式if (s[0] == 'x') {if (s[i + 1] != '\0' && s[i + 1] == '^')a = 1;elseb = 1;}while (s[i] != '\0') {while ('0' <= s[i] && s[i] <= '9') {num = num * 10 + (s[i] - '0');i++;}if (s[i] == 'x') {if ((s[i + 1] != '\0' && s[i + 1] != '^') || (s[i + 1] == '\0')) {if (flag == 1)b += num;elseb -= num;num = 0;i++;} else { // 二次方if (flag == 1)a += num;elsea -= num;num = 0;i = i + 3; // 跳过^和次方}} else if (s[i] == '+') {if (s[i + 1] == 'x')b++;i++;flag = 1;num = 0;} else if (s[i] == '-') {if (s[i + 1] == 'x')b--;i++;flag = 0;num = 0;}}if (flag == 1)c += num;elsec -= num;} else { // 右边等式if (s[0] == 'x') {if (s[i + 1] != '\0' && s[i + 1] == '^')a = 1;elseb = 1;}while (s[i] != '\0') {while ('0' <= s[i] && s[i] <= '9') {num = num * 10 + (s[i] - '0');i++;}if (s[i] == 'x') {if ((s[i + 1] != '\0' && s[i + 1] != '^') || (s[i + 1] == '\0')) {if (flag == 1)b -= num;elseb += num;num = 0;i++;} else { // 二次方if (flag == 1)a -= num;elsea += num;num = 0;i = i + 3; // 跳过^和次方}} else if (s[i] == '+') {if (s[i + 1] == 'x')b--;i++;flag = 1;num = 0;} else if (s[i] == '-') {if (s[i + 1] == 'x')b++;i++;flag = 0;num = 0;}}if (flag == 1)c -= num;elsec += num;}
}int main() {char s[200], s1[100], s2[100];while (gets(s)) {int i = 0;int len = strlen(s);while (s[i] != '=')i++;subStr(s, s1, 0, i - 1);subStr(s, s2, i + 1, len - 1);a = b = c = 0;process(s1, 0);process(s2, 1);double der = b * b - 4 * a * c;if (der < 0)printf("No Solution\n");else {double x1 = (-b + sqrt(der)) / (2 * a);double x2 = (-b - sqrt(der)) / (2 * a);if (x1 < x2) {double tmp = x1;x1 = x2;x2 = tmp;}printf("%.2f %.2f\n", x2, x1);}}return 0;
}