算法训练 前缀表达式 (蓝桥杯)

 算法训练 前缀表达式  

时间限制:1.0s   内存限制:512.0MB

问题描述

  编写一个程序,以字符串方式输入一个前缀表达式,然后计算它的值。输入格式为:“运算符 对象1 对象2”,其中,运算符为“+”(加法)、“-”(减法)、“*”(乘法)或“/”(除法),运算对象为不超过10的整数,它们之间用一个空格隔开。要求:对于加、减、乘、除这四种运算,分别设计相应的函数来实现。
  输入格式:输入只有一行,即一个前缀表达式字符串。
  输出格式:输出相应的计算结果(如果是除法,直接采用c语言的“/”运算符,结果为整数)。
  输入输出样例

样例输入

+ 5 2

样例输出

7
 

ps:http://lx.lanqiao.org/problem.page?gpid=T225

谁能告诉我,错哪了。。。。。。无爱了!

#include<stdio.h>
#include<stack>
#include<string.h>
using namespace std;

stack<int> s;
void fun(char op)
{
 //   printf("%c
",op);
    int x,y;
    if(s.empty()) return ;
    x=s.top();
    s.pop();
 //   printf("%d
",x);
    if(s.empty()) return ;
    y=s.top();
    s.pop();
 //   printf("x=%d,y=%d
",x,y);
    switch(op)
    {
        case'+':x+=y; break;
        case'-':x-=y; break;
        case'*':x*=y; break;
        case'/':x/=y; break;
    }
    s.push(x);
}
char ch[10005];
int main()
{
    int len,x,y;

    gets(ch);
//    printf("%s
",ch);
    len=strlen(ch);
//    printf("%d
",len);
    for(int i=len-1;i>=0;i--)
    {
        if(ch[i]==' ') continue;
 //       printf("%c",ch[i]);
        if(ch[i]>='0'&&ch[i]<='9')
        {
            int xx=ch[i]-'0';
            s.push(xx);
        }
        else if(ch[i]=='+') fun(ch[i]);
        else if(ch[i]=='-') fun(ch[i]);
        else if(ch[i]=='*') fun(ch[i]);
        else if(ch[i]=='/') fun(ch[i]);
    }
    if(!s.empty())
    printf("%d
",s.top());
    s.pop();
    return 0;
}
 然后网上搜了一下,我更加无语了。。。。。。。。。。
#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    char c;
    int n,m;
    scanf("%c",&c);
    scanf("%d%d",&n,&m);
    if(c=='+')
        printf("%d
",n+m);
    if(c=='-')
        printf("%d
",n-m);
    if(c=='*')
        printf("%d
",n*m);
    if(c=='/')
        printf("%d
",n/m);
    return 0;
}
View Code

这代码居然能过。。。。。

 

大神们快来拯救我。帮我看下代码;

原文地址:https://www.cnblogs.com/yuyixingkong/p/4388496.html