bài tập ôg thầy ra đêy mấy ku debug lại rùi cùng nhau... nộp ^^
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
//------------------------------------------------------------------------------
const int MAX_STRING_LEN = 256;
typedef char String[MAX_STRING_LEN + 1]; // Plus '\0' character
//------------------------------------------------------------------------------
void Input(String infix)
{
do
{
printf("Nhap bieu thuc cong tru nhan chia: ");
gets(infix);
} while (infix[0] == '\0');
// Remove spaces
int i, j = 0;
for (i = 0; infix[i] != '\0'; i++)
if (!isspace(infix[i]))
{
infix[j] = infix[i];
j++;
}
infix[j] = '\0';
}
//------------------------------------------------------------------------------
char isNumberChar(char k)
{
return (isdigit(k) || k == '.');
}
//------------------------------------------------------------------------------
char isOperator(char k)
{
return (k == '*' || k == '/' || k == '+' || k == '-');
}
//------------------------------------------------------------------------------
char isLargerOrSame(char x, char y)
{
return (x == '*' || x == '/' || y == '+' || y == '-');
}
//------------------------------------------------------------------------------
void BuildPostfix(String postfix, String infix)
{
String stack;
int slen = 0; // Length of stack
int plen = 0; // Length of postfix
int i, j;
for (i = 0; infix[i] != '\0'; i++)
if (isNumberChar(infix[i]))
{
postfix[plen] = infix[i];
plen++;
}
else if (infix[i] == ')')
{
for (j = slen - 1; (j >= 0) && (stack[j] != '('); j--)
{
postfix[plen] = stack[j];
plen++;
}
slen = j;
}
else
{
if (isOperator(infix[i]))
{
while (slen > 0
&& stack[slen - 1] != '('
&& isLargerOrSame(stack[slen - 1], infix[i]))
{
slen--;
postfix[plen] = stack[slen];
plen++;
}
postfix[plen] = ' ';
plen++;
}
stack[slen] = infix[i];
slen++;
}
// Add all remaining
while (slen > 0)
{
postfix[plen] = stack[slen - 1];
slen--;
plen++;
}
postfix[plen] = '\0';
}
//------------------------------------------------------------------------------
double GetResult(String postfix)
{
double stack[MAX_STRING_LEN / 2];
int slen = 0;
int i, j;
for (i = 0; postfix[i] != '\0'; i++)
{
if (isNumberChar(postfix[i]) && !isNumberChar(postfix[i + 1]))
{
j = i;
while (j > 0 && isNumberChar(postfix[j - 1]))
j--;
sscanf(postfix + j, "%lf", &stack[slen]);
slen++;
}
else if (isOperator(postfix[i]))
{
slen--;
if (postfix[i] == '*')
stack[slen - 1] *= stack[slen];
else if (postfix[i] == '/')
stack[slen - 1] /= stack[slen];
else if (postfix[i] == '+')
stack[slen - 1] += stack[slen];
else if (postfix[i] == '-')
stack[slen - 1] -= stack[slen];
}
}
return stack[0];
}
//------------------------------------------------------------------------------
int main()
{
String infix, postfix;
Input(infix);
printf("Trung to: %s\n", infix);
BuildPostfix(postfix, infix);
printf("Hau to: %s\n", postfix);
printf("Ket qua: %lf", GetResult(postfix));
return EXIT_SUCCESS;
}