// 1019_簡單計算器.cpp : 定義控制檯應用程序的入口點。
//1019:簡單計算器
//時間限制:1 秒內存限制:32 兆特殊判題:否提交:8585解決:3134
//題目描述:
// 讀入一個只包含 +, -, *, / 的非負整數計算表達式,計算該表達式的值。
//輸入:
// 測試輸入包含若干測試用例,每個測試用例佔一行,每行不超過200個字符,整數和運算符之間用一個空格分隔。沒有非法表達式。當一行中只有0時輸入結束,相應的結果不要輸出。
//輸出:
// 對每個測試用例輸出1行,即該表達式的值,精確到小數點後2位。
//樣例輸入:
//1 + 2
//4 + 2 * 5 - 7 / 11
//0
//樣例輸出:
//3.00
//13.36
#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#define MAX 1001
double stack[MAX];
int tail;
int main(){
int a;
while(scanf("%d ",&a)&&a!=0){
tail=0;
stack[++tail]=1.0*a;//tail始終指向末尾數字位置
//1.入棧所有數據(如果遇到*/號,只更新棧尾)
char ch1,ch2;
while(scanf("%c %d%c",&ch1,&a,&ch2)!=EOF){
if(ch1=='+'){
stack[++tail]=1.0*a;//push
}else if(ch1=='-'){
stack[++tail]=-1.0*a;//關鍵是把減法變爲加法
}else if(ch1=='*'){
stack[tail]=stack[tail]*a;//update tail
}else if(ch1=='/'){
stack[tail]=stack[tail]/(double)a;//updata tail
}
if(ch2!=' ')break;
}
//2.把棧裏頭的東西全部加起來,求和
double result=0;
for(int i=1;i<=tail;i++)result+=stack[i];
printf("%.2lf\n",result);
}
return 0;
}
//#include "stdio.h"
//#include "string.h"
//#include "stdlib.h"
//
//#define is_op(x) !strcmp("+",x)|!strcmp("-",x)|!strcmp("*",x)|!strcmp("/",x)
//
//typedef struct stack{
// double digit[200];
// char op[200];
// int top_digit;
// int top_op;
//}stack;
//
//double calculate(double a,char c,double b)
//{
// if(c == '+')
// return a+b;
// else if(c == '-')
// return a-b;
// else if(c == '*')
// return a*b;
// else if(c == '/')
// return a/b;
//}
//
//int main()
//{
// char c;
// char line[202];
// while(gets(line))
// {
// int len = strlen(line);
// char *token = " ";
// char *result = strtok(line,token);
// stack s;
// s.digit[0] = -1.0;
// s.op[0] = '#';
// s.top_digit = 0;
// s.top_op = 0;
// while(result)
// {
// //if(!strcmp(result,"+"))
// if(is_op(result))
// {
// //printf("%c",result[0]);
// //break;
// s.op[++s.top_op] = result[0];
// //printf("%c",s.op[s.top_op]);
// }
// else
// {
// double num = atof(result);
// char temp = s.op[s.top_op];
// if(temp == '+' || temp == '-' || temp/ == '#')
// {
// //s.top_digit++;
// s.digit[++s.top_digit] = (double)num;
//
// }
// else
// {
// double d = s.digit[s.top_digit--];
// double result = calculate(d,temp,num);
// s.digit[++s.top_digit] = result;
// }
// //printf("%d\n",num);
//
// }
// //else if(!strcmp(*result,""))
// }
// //printf("%c ",c);
// }
// /*char a[100];
// gets(a);
// printf("%c",a[1]);
// if(a[1] == '\n')
// printf("ddddddd");
// else if(a[1] == '\0')
// printf("zzzzzz");
// printf("%s",a);*/
// return 0;
//}
1019_簡單計算器
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.