#include <iostream>
usingnamespace std;
usingnamespace std;
constchar * expressionToParse = "6.5-2.5*10/5+2*5";
char peek()
{
return *expressionToParse;
}
char get()
{
return *expressionToParse++;
}
double expression();
double number()
{
double result = get() - '0';
while (peek() >= '0' && peek() <= '9')
{
result = 10*result + get() - '0';
}
return result;
}
double factor()
{
if (peek() >= '0' && peek() <= '9')
return number();
elseif (peek() == '(')
{
get(); // '('
double result = expression();
get(); // ')'
return result;
}
elseif (peek() == '-')
{
get();
return -expression();
}
return 0; // error
}
double term()
{
double result = factor();
while (peek() == '*' || peek() == '/')
if (get() == '*')
result *= factor();
else
result /= factor();
return result;
}
double expression()
{
double result = term();
while (peek() == '+' || peek() == '-')
if (get() == '+')
result += term();
else
result -= term();
return result;
}
int main(double argc, char* argv[])
{
double result = expression();
cout << result << endl;
return 0;
}
The problem is that it does not work properly with decimal numbers
for example it evaluates 6-2*10/5+2*5 = 12 which is correct but for 6.5-2.5*10/5+2*5 it returns 6 instead of 11.5 .
can someone please help me to fix this issue ?