- 题目描述:
-
设计一个二次方程计算器
- 输入:
-
每个案例是关于x的一个二次方程表达式,为了简单,每个系数都是整数形式。
- 输出:
-
每个案例输出两个实数(由小到大输出,中间由空格隔开),保留两位小数;如果无解,则输出“No Solution”。
- 样例输入:
-
x^2+x=3x+4
- 样例输出:
-
-1.24 3.24
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <algorithm> 5 #include <cmath> 6 #define MAX 102 7 8 char er[MAX]; 9 int main(int argc, char const *argv[]) 10 { 11 int n, m, k; 12 //freopen("input.txt","r",stdin); 13 while(scanf("%s",er) != EOF) { 14 int a = 0, b = 0, c = 0; 15 int state = 1; 16 int i = 0; 17 int temp = 1; 18 int fu = 1; 19 while(i < strlen(er)) { 20 if(er[i] == 'x' && i+2 < strlen(er)) { 21 if(er[i+1] == '^' && er[i+2] == '2') { 22 temp = temp * fu; 23 a = a + temp; 24 i = i + 3; 25 temp = state; 26 } 27 else { 28 temp = temp * fu; 29 b = b + temp; 30 i++; 31 temp = state; 32 } 33 } 34 else if(er[i] == 'x') { 35 temp = temp * fu; 36 b = b + temp; 37 i++; 38 temp = state; 39 } 40 else if(er[i] == '-') { 41 fu = -1; 42 i++; 43 } 44 else if(er[i] == '+') { 45 fu = 1; 46 i++; 47 } 48 else if(er[i] >= '0' && er[i] <= '9') { 49 temp = 0; 50 while(er[i] >= '0' && er[i] <= '9') { 51 temp = temp * 10 + er[i] - '0'; 52 i++; 53 } 54 temp = temp * state; 55 if((i < strlen(er) && er[i] != 'x') || i == strlen(er)) { 56 temp = temp * fu; 57 c = c + temp; 58 temp = state; 59 } 60 } 61 else if(er[i] == '=') { 62 state = -1; 63 temp = state; 64 fu = 1; 65 i++; 66 } 67 } 68 //printf("%d %d %d ",a,b,c); 69 double at = a, bt = b, ct = c; 70 double ansa, ansb; 71 double dt = bt*bt-4*at*ct; 72 if( dt < 0) { 73 puts("No Solution"); 74 } 75 else { 76 ansa = (-bt - sqrt(dt))/(2*at); 77 ansb = (-bt + sqrt(dt))/(2*at); 78 printf("%.2lf %.2lf ",ansa, ansb); 79 } 80 } 81 return 0; 82 }