ACM问题 我的代码哪里错了呢???? http://acm.swjtu.edu.cn/JudgeOnline/showproblem?problem_id=1314
Mikeisamiddleschoolteacher.Heisteachingmathematics.Aftereachchapter,healwaysarrangess...
Mike is a middle school teacher. He is teaching mathematics. After each chapter, he always arranges some homework to his students. In this chapter, he will ask his students to calculate the value of some expressions. There are many brackets in these expressions. Sometimes it is very difficult to find whether these brackets are match or not. In other time, it’s difficult to find whether the brackets are at the right positions. Please write a program to help him to check these expressions.
Input
Input includes n+1 lines, the first of these lines is an integer number n, which implies that there are n expressions to be checked. Each line represents one expression which includes double number, +,-,*,/ operator or (,) brackets.
Output
For each expression, output one word ‘Legal’ or ‘Illegal’.
Sample Input
2
2.3+(4.5+3.678)/3.4*2.5+(3.4+(4.5-(2.3)*3)
4.5+(4.2324*3.8)-3.4*(1.5-(3.4*(5.6/(3.6-(2.8)))))
Sample Output
Illegal
Legal
我的代码:
#include<iostream>
#include<stdio.h>
#include<stack>
using namespace std;
int main()
{
int t,i=0;
char ch;
cin>>t;
getchar();
while(t--)
{
stack<char>stack1;
while(1)
{
scanf("%c",&ch);
switch(ch)
{
case '(':
stack1.push(ch);
break;
case ')':
stack1.pop();
break;
}
if(ch=='\n')
{
if(stack1.empty())
cout<<"Legal"<<endl;
else
cout<<"Illegal"<<endl;
break;
}
}
}
return 0;
} 展开
Input
Input includes n+1 lines, the first of these lines is an integer number n, which implies that there are n expressions to be checked. Each line represents one expression which includes double number, +,-,*,/ operator or (,) brackets.
Output
For each expression, output one word ‘Legal’ or ‘Illegal’.
Sample Input
2
2.3+(4.5+3.678)/3.4*2.5+(3.4+(4.5-(2.3)*3)
4.5+(4.2324*3.8)-3.4*(1.5-(3.4*(5.6/(3.6-(2.8)))))
Sample Output
Illegal
Legal
我的代码:
#include<iostream>
#include<stdio.h>
#include<stack>
using namespace std;
int main()
{
int t,i=0;
char ch;
cin>>t;
getchar();
while(t--)
{
stack<char>stack1;
while(1)
{
scanf("%c",&ch);
switch(ch)
{
case '(':
stack1.push(ch);
break;
case ')':
stack1.pop();
break;
}
if(ch=='\n')
{
if(stack1.empty())
cout<<"Legal"<<endl;
else
cout<<"Illegal"<<endl;
break;
}
}
}
return 0;
} 展开
1个回答
展开全部
注意看题目,有两种情况不合法:
1)Sometimes it is very difficult to find whether these brackets are match or not.
2)In other time, it’s difficult to find whether the brackets are at the right positions.
你的代码忽略了第二条,只判断了括号是否匹配,没有判断括号是否放在合适的位置。
比如你试试这个:
3(2)
显然是个不合法表达式,不过你的代码会认为它合法。
1)Sometimes it is very difficult to find whether these brackets are match or not.
2)In other time, it’s difficult to find whether the brackets are at the right positions.
你的代码忽略了第二条,只判断了括号是否匹配,没有判断括号是否放在合适的位置。
比如你试试这个:
3(2)
显然是个不合法表达式,不过你的代码会认为它合法。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询