写了好久终于写出来了,这段代码可以解决小数和正负数。
提交时间 | 分数 | 题目 | 编译器 | 耗时 | 用户 | |
---|---|---|---|---|---|---|
2022/10/13 17:43:48 | 答案正确 | 20 | C++ (g++) | 5 ms | 20211205040 |
测试点 | 提示 | 结果 | 分数 | 耗时 | 内存 |
---|---|---|---|---|---|
0 | sample 6种运算符 | 答案正确 | 10 | 4 ms | 324 KB |
1 | 嵌套括号 | 答案正确 | 4 | 5 ms | 324 KB |
2 | 运算数超过1位整数且有非整数出现 | 答案正确 | 3 | 4 ms | 312 KB |
3 | 运算数前有正负号 | 答案正确 | 2 | 5 ms | 320 KB |
4 | 只有1个数字 | 答案正确 | 1 | 4 ms | 452 KB |
对代码进行以下解释。
输出思路为:
第一个输出——那么只输出内容(内容指一位或多位数,符号)
如果不是第一个输出——先输出一个空格,然后再输出内容
宏变量First用于确定第一个输出的数,如果还没有输出第一个内容,则First=0,在输出内容前不加空格 ;如果输出了第一个内容,则First=1,在输出内容前要加空格
numHandle1和numHandle2都是处理数字的,不同点是后者在遇到+-时判断,用于处理带符号数字,前者在遇到第一个数字时判断,用于处理不带符号的数字
代码一开始的 s.append(1,'$'); 是防止在多位小数判断时使用++i 时发生越界,造成错误,不可删去
因为第一个输出的数字只可能是数字,所以在判断First时只对数字进行了判断
在for循环前的 else 语句减1,是为了处理第一个符号是括号时,for循环需要判断的第一个字符仍为s[0],则减1和for中的加1抵消,和为0(numHandle1和numHandle2返回的都是处理后的数字串末尾的值)
第42行语句 j=i ,说明在完成函数后i没有移动,也就说明了+-不是数字符号,则把他作为运算符处理
#include <iostream>
#include <string.h>
#include <stack>
using namespace std;
int IsNumber(string s,int i);
int numHandle1(string s,int i);
int numHandle2(string s,int i);
int judgePriority(char a,char b);
int getPriority(char x);
int First=0;
int main()
{
string num,s;
getline(cin,s);
int len=s.length();
s.append(1,'$');
stack<char> stack1;
int i=0;
if( strchr("+-",s[i]) ) i=numHandle1(s,i);
else if( IsNumber(s,0) ) i=numHandle2(s,i);
else i--;
for(++i;i<len;i++)//输出全部前加空格
{
//cout<<"i="<<i<<endl;
if(s[i]=='(') stack1.push('(');
else if(s[i]==')')//一直弹栈
{
while(stack1.top()!='(')
{
cout<<' '<<stack1.top();
stack1.pop();
}stack1.pop();
}
else if(IsNumber(s,i)==1) i=numHandle2(s,i);
else if(strchr("+-",s[i]))
{
int j=numHandle1(s,i);//i为发现+-的位置
if(i==j)//不是数字
{
while(!stack1.empty())
{
int is=judgePriority(s[i],stack1.top());
if(!is)
{
cout<<' '<<stack1.top();
stack1.pop();
}
else break;
}
stack1.push(s[i]);
}
else i=j;//是数字,已经处理完了
}
else if(strchr("*/\\",s[i]))
{
while(!stack1.empty())
{
int is=judgePriority(s[i],stack1.top());
if(!is)
{
cout<<' '<<stack1.top();
stack1.pop();
}
else break;
}
stack1.push(s[i]);
}
}
while(!stack1.empty())
{
cout<<' '<<stack1.top();
stack1.pop();
}
return 0;
}
int getPriority(char x)
{
if(x=='(') return 0;
else if(strchr("+-",x)) return 1;
else if(strchr("*/\\",x)) return 2;
}
int judgePriority(char a,char b)
{
int now=getPriority(a),bi=getPriority(b);
if(now>bi)return 1;
else return 0;
}
int numHandle1(string s,int i)//i为发现+-的位置
{
string str;
int j=0;
if(i==0||( !IsNumber(s,i-1)&&s[i-1]!=')' ))//是数字正负号
{
if(!First) First++;
else cout<<' ';
if(s[i]=='-')
cout<<s[i];//正号不输出
while(1)
{
i++;
if( IsNumber(s,i) ) cout<<s[i];
else break;
}
return i-1;
}
else return i;//不是数字正负号
}
int numHandle2(string s,int i)//i为首先发现数字的位置
{
if(!First) First++;
else cout<<' ';
cout<<s[i];
while(1)
{
i++;
if( IsNumber(s,i) ) cout<<s[i];
else break;
}
return i-1;
}
int IsNumber(string s,int i)
{
if(strchr("0123456789",s[i])) return 1;
else if(s[i]=='.')return 2;
else return 0;
}