算法训练 前缀表达式

来源:互联网 发布:二分搜索算法递归程序 编辑:程序博客网 时间:2024/05/21 02:53
问题描述
  编写一个程序,以字符串方式输入一个前缀表达式,然后计算它的值。输入格式为:“运算符 对象1 对象2”,其中,运算符为“+”(加法)、“-”(减法)、“*”(乘法)或“/”(除法),运算对象为不超过10的整数,它们之间用一个空格隔开。要求:对于加、减、乘、除这四种运算,分别设计相应的函数来实现。
  输入格式:输入只有一行,即一个前缀表达式字符串。
  输出格式:输出相应的计算结果(如果是除法,直接采用c语言的“/”运算符,结果为整数)。
  输入输出样例
样例输入
+ 5 2
样例输出
7
我的答案:
import java.util.Scanner;public class Main {public static void main(String[]args){Scanner sc=new Scanner(System.in);String s=sc.next();char ch=s.charAt(0);String str=s.substring(s.length()-2,s.length());int a=(Integer.parseInt(str))/10;int b=(Integer.parseInt(str))%10;switch(ch){case '+':System.out.println(a+b);break;case '-':System.out.println(a-b);break;case '*':System.out.println(a*b);break;case '/':System.out.println(a/b);break;}sc.close();}}

测试结果:GG



网上答案:
#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",n+m);    if(c=='-')        printf("%d\n",n-m);    if(c=='*')        printf("%d\n",n*m);    if(c=='/')        printf("%d\n",n/m);    return 0;}

测试结果:AA


题目要求:

END:
迷之微笑
1 0