#include<iostream> #include<stack> #include<string.h> using namespace std; stack<int> stk; char temp[1005] = {}; int A() { int sum = 0; for (int i = 0; i < strlen(temp); ++i) { if (temp[i] == '&') break; sum = sum * 10 + temp[i] - '0'; temp[i] = '&'; } return sum; } int main() { int tmp = 0; char fuhao; int a1, a2; int idx = 0; while (fuhao != '@') { cin >> fuhao; if (fuhao >= '0' && fuhao <= '9') { temp[idx] = fuhao; idx++; } if (fuhao == '.') { idx = 0; tmp = A(); stk.push(tmp); } if (fuhao == '+') { a1 = stk.top(); stk.pop(); a2 = stk.top(); stk.pop(); stk.push(a1 + a2); } if (fuhao == '-') { a1 = stk.top(); stk.pop(); a2 = stk.top(); stk.pop(); stk.push(a2 - a1); } if (fuhao == '*') { a1 = stk.top(); stk.pop(); a2 = stk.top(); stk.pop(); stk.push(a1 * a2); } if (fuhao == '/') { a1 = stk.top(); stk.pop(); a2 = stk.top(); stk.pop(); stk.push(a2 / a1); } } cout << stk.top() << endl; return 0; }不使用string和stack的STL容器实现这个代码
时间: 2024-01-19 10:03:02 浏览: 125
#include"iostream.h"
3星 · 编辑精心推荐
以下是不使用 STL 容器实现的代码:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int stack[1005];
char temp[1005];
int top = -1;
int A() {
int sum = 0;
for (int i = 0; i < strlen(temp); ++i) {
if (temp[i] == '&') break;
sum = sum * 10 + temp[i] - '0';
temp[i] = '&';
}
return sum;
}
int main() {
int tmp = 0;
char fuhao;
int a1, a2;
int idx = 0;
while (fuhao != '@') {
cin >> fuhao;
if (fuhao >= '0' && fuhao <= '9') {
temp[idx] = fuhao;
idx++;
}
if (fuhao == '.') {
idx = 0;
tmp = A();
top++;
stack[top] = tmp;
}
if (fuhao == '+') {
a1 = stack[top];
top--;
a2 = stack[top];
top--;
top++;
stack[top] = a1 + a2;
}
if (fuhao == '-') {
a1 = stack[top];
top--;
a2 = stack[top];
top--;
top++;
stack[top] = a2 - a1;
}
if (fuhao == '*') {
a1 = stack[top];
top--;
a2 = stack[top];
top--;
top++;
stack[top] = a1 * a2;
}
if (fuhao == '/') {
a1 = stack[top];
top--;
a2 = stack[top];
top--;
top++;
stack[top] = a2 / a1;
}
}
cout << stack[top] << endl;
return 0;
}
```
阅读全文