839.2011.C.十一.2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAXN 100
char str[MAXN];
int num,ratio;

//先把一些特殊情况特判掉
char* getV(char *s, int *n1, int *flag)
{
if(isalpha(*s))
{
*n1 = 1,*flag = 0;
return s+1;
}
if((*s == '+' || *s == '-') && isalpha(*(s+1)))
{
*n1 = (*s=='+'?1:-1), *flag = 0;
return s+2;
}
char ch;
int sgn = 1;
*n1 = *flag = 0;
while(*s)
{
ch = *s++;
if(ch == '+') sgn *= 1;
if(ch == '-') sgn *= -1;
if(isdigit(ch)) *n1 = (*n1)*10 + (ch - '0');
if(isalpha(*s) || *s == '+' || *s == '-')
break;
}
(*n1) *= sgn;
if(isalpha(*s))
{
*flag = 0;
return s+1;
}
*flag = 1;
return s;
}

void process(char * hequ)
{
int n1 = 0,flag = 0;
while(*hequ)
{
hequ = getV(hequ, &n1, &flag);
if(flag) num += n1;//flag=1表示是数字
else ratio += n1;//flag=0表示是变量
}
}

double calcEquation(char* equation)
{
int len = strlen(equation);
char *p1 = equation;
char *p2 = NULL;
for(int i = 0; i < len; ++i)
{
if(equation[i] == '=')
{
p2 = equation+i+1;
equation[i] = '\0';
break;
}
}
// puts(p1);puts(p2);
num = ratio = 0;
process(p1);
num = -num, ratio = -ratio;
process(p2);
double ret = (-num)/(double)ratio;
return ret;
}
//6a-5+1=2-2a
//只考虑所有方程式都是合法的情况
int main()
{
scanf("%s",str);
double res = calcEquation(str);
printf("%.3f",res);
return 0;
}