一元多项式简单计算器
发布网友
发布时间:2022-05-03 02:13
我来回答
共1个回答
热心网友
时间:2022-07-01 12:31
#include <iostream>
#include <cstdlib>
#include <cctype>
using namespace std;
void eatspaces(char* str);
double expr(char* str);
double term(char* str,int& index);
double number(char* str,int& index);
char* extract(char* str, int& index);
const int MAX = 80;
int main()
{
char buffer[MAX] = {0};
cout<< endl
<< "欢迎使用计算器"<<endl
<<"请输入表达式进行计算或者输入空白行退出"<<endl;
for(;;)
{
cin.getline(buffer,sizeof buffer);
eatspaces(buffer);
if(!buffer[0])
return 0;
cout<<"\t="<<expr(buffer)
<<endl<<endl;
}
}
void eatspaces(char* str)
{
int i = 0;
int j = 0;
while((*(str + i)= *(str + j++)) !='\0')
if(*(str + i) != ' ')
i++;
return;
}
double expr(char* str)
{
double value = 0.0;
int index = 0;
value = term(str,index);
for(;;)
{
switch(*(str + index++))
{
case '\0':
return value;
case '+':
value += term(str,index);
break;
case '-':
value -= term(str,index);
break;
default:
cout<<endl
<<"输入错误"
<<endl;
exit(1);
}
}
}
double term(char* str, int& index)
{
double value = 0.0;
value = number(str, index);
while((*(str + index) == '*')||(*(str + index) == '/'))
{
if(*(str + index) == '*')
value *= number(str, ++index);
if(*(str + index) == '/')
value /= number(str,++index);
}
return value;
}
double number(char* str,int& index)
{
double value = 0.0;
if(*(str + index) == '(')
{
char* psubstr = 0;
psubstr = extract(str,++index);
value = expr(psubstr);
delete[]psubstr;
return value;
}
while(isdigit(*(str + index)))
value = 10*value + (*(str + index++) - 48);
if(*(str + index)!= '.')
return value;
double factor = 1.0;
while(isdigit(*(str + (++index))))
{
factor = value + (*(str + index) - 48)*factor;
}
return value;
}
char* extract(char* str, int& index)
{
char buffer[MAX];
char* pstr = 0;
int numL = 0;
int bufindex = index;
do
{
buffer[index - bufindex] = *(str + index);
switch(buffer[index - bufindex])
{
case ')':
if(numL == 0)
{
buffer[index - bufindex] = '\0';
++index;
pstr = new char[index - bufindex];
if(!pstr)
{
cout<<"输入错误"<<endl;
exit(1);
}
strcpy_s(pstr,index-bufindex,buffer);
return pstr;
}
else
numL--;
break;
case '(':
numL++;
break;
}
}while(*(str + index++) != '\0');
cout<<"输入错误"<<endl;
exit(1);
return pstr;
}
----------------------------------
本人也是学生,不是高手,大家共同学习,共同进步。回答可能不是完全正确,希望原谅。