今天去腾讯广州笔试去了,结果很悲剧。不过没关系,只有在不断的被鄙视的过程中才能茁壮成长,加油!
1.输入:一个字符串,其中包括四种运算符:+、-、*、/和一些整数(0-9)。PS:没有括号。
输出:运算结果(double)。实例:输入1*2+4/2-4+5 输出:5.0
分析:先把乘除运算做完,把减运算变成后面那个数的负数,并把前三种运算的结果输入到栈中。后面的就全部是加运算了。
代码:
#include <iostream>
#include <stdlib.h>
#include <stack>
using namespace std;
double Calc(const char *str)
{
stack <double> data;
int i=0;
double result,temp;
while(str[i]!='\0')
{
switch(str[i])
{
case '+':
break;
case '-':
temp=-(str[++i]-'0');
data.push(temp);
break;
case '*':
result=data.top();
data.pop();
temp=str[++i]-'0';
result*=temp;
data.push(result);
break;
case '/':
result=data.top();
data.pop();
temp=str[++i]-'0';
result/=temp;
data.push(result);
break;
default:
result=str[i]-'0';
data.push(result);
break;
}
i++;
}
while(data.size()>1)
{
result=data.top();
data.pop();
temp=data.top();
data.pop();
result+=temp;
data.push(result);
}
result=data.top();
data.pop();
return result;
}
int main()
{
char str[30];
cin>>str;
cout<<Calc(str)<<endl;
return 0;
}
如果把整数变成多位,算法如下:
#include <iostream>
#include <stack>
#include <stdlib.h>
using namespace std;
int GetData(const char *str,int *i)
{
int size=strlen(str)-1,j=0;
char ch[size];
while(true)
{
if(str[j]=='+'||str[j]=='-'||str[j]=='*'||str[j]=='/'||str[j]=='\0')
break;
else
{
ch[j]=str[j];
j++;
(*i)++;
}
}
(*i)--;
ch[j]='\0';
return atoi(ch);
}
double Calc(const char *str)
{
stack <double> data;
char ch;
int i=0;
double result,temp;
while(str[i]!='\0')
{
switch(str[i])
{
case '+':
break;
case '-':
i++;
temp=-GetData(str+i,&i);;
data.push(temp);
break;
case '*':
result=data.top();
data.pop();
i++;
temp=GetData(str+i,&i);;
result*=temp;
data.push(result);
break;
case '/':
result=data.top();
data.pop();
i++;
temp=GetData(str+i,&i);
result/=temp;
data.push(result);
break;
default:
result=GetData(str+i,&i);
data.push(result);
break;
}
i++;
}
while(data.size()>1)
{
result=data.top();
data.pop();
temp=data.top();
data.pop();
result+=temp;
data.push(result);
}
result=data.top();
data.pop();
return result;
}
int main()
{
char str[50];
cin>>str;
cout<<Calc(str)<<endl;
return 0;
}
本文详细介绍了如何使用C++语言编写一个程序来解析包含多种运算符和数字的字符串表达式,并实现了从左到右依次进行乘除运算,最后将所有加法运算整合为最终结果的计算过程。通过代码示例,演示了如何使用栈数据结构来处理运算符优先级的问题,确保了表达式的正确计算。
1004

被折叠的 条评论
为什么被折叠?



