#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
//执行计算过程的子函数
double calc(double * pNum, char* pCh, unsigned int a);
int main()
{
double* pNum = NULL; //用于存储数字
char* pCh = NULL; //用于存储符号
AA: pNum = (double*)malloc(sizeof(double)); //分配一个double内存空间
pCh = (char*)malloc(sizeof(char)); //分配一个char型内存空间
scanf("%lf%c", pNum, pCh);
unsigned int a = 2; //用于动态内存分配
while (*(pCh+a-2) != '=') //只要输入的符号不是‘=’
{
pNum = (double*)realloc(pNum,a*sizeof(double)); //增加一个double型空间
pCh = (char*)realloc(pCh,a*sizeof(char)); //增加一个char型内存空间
scanf("%lf%c", pNum+a-1, pCh+a-1);
a++;
}
//将最后的结果移到输入多项式的等号后面
for (unsigned int i = 0; i < a-1; i++)
{
printf(" ");
}
double value = calc(pNum, pCh, a - 1); //调用计算函数
printf("%lf\n\n",value); //输出计算结果
free(pNum); //释放内存
free(pCh); //释放内存
goto AA; //跳回,准备接收下一个多项式
system("pause");
return 0;
}
//用于计算多项式
double calc(double * pNum, char* pCh, unsigned int a)
{
unsigned i = 0;
//先遍历多项式,计算出乘除
while (*(pCh + i) != '=')
{
if (*(pCh + i) == '*')
{
//计算并移位
*(pNum + i) = (*(pNum + i)) * (*(pNum + i + 1));
*(pCh + i) = *(pCh + i + 1);
for (unsigned int j = i + 1; j < a - 1; j++)
{
pNum[j] = pNum[j + 1];
pCh[j] = pCh[j + 1];
}
a--;
i--;
//用于调试的代码
//for (unsigned int i = 0; i < a; i++)
//{
// printf("%d%c", pNum[i], pCh[i]);
//}
//printf("\n");
}
else if (*(pCh + i) == '/')
{
*(pNum + i) = (*(pNum + i)) / (*(pNum + i + 1));
*(pCh + i) = *(pCh + i + 1);
for (unsigned int j = i + 1; j < a - 1; j++)
{
pNum[j] = pNum[j + 1];
pCh[j] = pCh[j + 1];
}
a--;
i--;
用于调试的代码
//for (unsigned int i = 0; i < a; i++)
//{
// printf("%d%c", pNum[i], pCh[i]);
//}
//printf("\n");
}
i++;
}
i = 0;
//再遍历多项式计算加减
while (*(pCh + i) != '=')
{
if (*(pCh + i) == '+')
{
*(pNum + i) = (*(pNum + i)) + (*(pNum + i + 1));
*(pCh + i) = *(pCh + i + 1);
for (unsigned int j = i + 1; j < a - 1; j++)
{
pNum[j] = pNum[j + 1];
pCh[j] = pCh[j + 1];
}
a--;
i--;
用于调试的代码
//for (unsigned int i = 0; i < a; i++)
//{
// printf("%d%c", pNum[i], pCh[i]);
//}
//printf("\n");
}
else if (*(pCh + i) == '-')
{
*(pNum + i) = (*(pNum + i)) - (*(pNum + i + 1));
*(pCh + i) = *(pCh + i + 1);
for (unsigned int j = i + 1; j < a - 1; j++)
{
pNum[j] = pNum[j + 1];
pCh[j] = pCh[j + 1];
}
a--;
i--;
用于调试的代码
//for (unsigned int i = 0; i < a; i++)
//{
// printf("%d%c", pNum[i], pCh[i]);
//}
//printf("\n");
}
i++;
}
return *pNum; //计算的结果存在pNum的第一个内存地址
}