Skip to content

Instantly share code, notes, and snippets.

@rigibun
Created July 16, 2013 07:31
Show Gist options
  • Save rigibun/6006581 to your computer and use it in GitHub Desktop.
Save rigibun/6006581 to your computer and use it in GitHub Desktop.
#include <cstdio>
#include <cstring>
using namespace std;
double expr(char*);
double term(char*);
double elem(char*);
double expr(char *a)
{
int id = 0, cnt = 0, s = 1;
double ret = 0;
while(1)
{
if(a[id] == '(')
cnt++;
if(a[id] == ')')
cnt--;
if( (a[id] == '+' || a[id] == '-' || a[id] == '\0') && cnt == 0)
{
char b[100];
strncpy(b, a, id);
b[id] = '\0';
ret += term(b) * s;
if(a[id] == '+')
s = 1;
else if(a[id] == '-')
s = -1;
else
break;
a += id + 1;
id = 0;
}
id++;
}
return ret;
}
double term(char *a)
{
int id = 0, cnt = 0;
double ret = 0;
bool s = true, f = true;
while(1)
{
if(a[id] == '(')
cnt++;
if(a[id] == ')')
cnt--;
if( (a[id] == '*' || a[id] == '/' || a[id] == '\0') && cnt == 0)
{
char b[100];
strncpy(b, a, id);
b[id] = '\0';
double e = elem(b);
if(f)
{
ret = e;
f = false;
}
else
{
if(s)
ret *= e;
else
ret /= e;
}
if(a[id] == '*')
s = true;
else if(a[id] == '/')
s = false;
else
break;
a += id + 1;
id = 0;
}
id++;
}
return ret;
}
double elem(char *a)
{
double ret = 0;
if(a[0] == '(')
{
a++;
a[strlen(a) - 1] = '\0';
ret = expr(a);
}
else
{
double e;
sscanf(a, "%lf", &e);
ret = e;
}
return ret;
}
int main()
{
char a[501];
fgets(a, 500, stdin);
a[strlen(a) - 1] = '\0';
printf("%.2lf\n", expr(a));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment