标签:字符串
1 + 2 4 + 2 * 5 - 7 / 11 0
3.00 13.36
分析:因为没有括号,所以我们可以按照:如果是数字进模拟队列,判断后面的符号是+-还是*/,如果是乘除将前面的(*=)或(/=)后面的就好,否则讲后面的进队列
#include <stdio.h> #include <iostream> #include <string.h> #include <string> #include <stdlib.h> #include <queue> #include <stack> using namespace std; char str[205]; int main(){ while(gets(str)){ int len = strlen(str), i, j, k, z; double fa, fb; double que[250]; for(i = 0; i < len; i ++) if(str[i] != '0') break; if(i == len) break; //str[len++] = ' '; str[len++] = ' '; str[len] = '\0'; char temp[205], ca[205]; int flag = 0; for(i = 0, j = 0, k = 0, z = 0; i < len; i ++){ if(str[i] >= '0'&&str[i] <= '9'){ temp[j++] = str[i]; } else if(i+1 < len){ temp[j++] = '\0'; //printf("%s... ", temp); //if(str[i+3] >= '0'&&str[i]) if(flag){ if(flag == 1) que[k-1]*= atol(temp); else que[k-1]/=atol(temp); flag = 0; } else que[k++] = atol(temp); if(str[i+1] == '*'){ flag = 1; } else if(str[i+1] == '/'){ flag = 2; } else ca[z++] = str[i+1]; i+=2; j = 0; } } temp[j] = '\0'; if(flag){ if(flag == 1) que[k-1]*= atol(temp); else que[k-1]/=atol(temp); flag = 0; } else que[k++] = atol(temp); /*for(i = 0; i < k; i ++) printf("%lf..\n", que[i]); for(i = 0; i < z; i ++) printf("%c..\n", ca[i]);*/ for(i = 1; i < k; i ++){ if(ca[i-1] == '+') que[i] += que[i-1]; else que[i] = que[i-1] - que[i]; } printf("%.2lf\n", que[k-1]); } return 0; }
标签:字符串
原文地址:http://blog.csdn.net/shengweisong/article/details/40750597