写一个计算器C++代码,200行
时间: 2024-01-08 11:04:08 浏览: 28
以下是一个比较完整的计算器C++代码示例,共计约200行。它支持基本的四则运算、括号、取模、取反、小数和科学计数法等功能。
```
#include <iostream>
#include <stack>
#include <cmath>
using namespace std;
// 定义优先级
int getPriority(char c) {
if(c == '(' || c == ')') return 0;
if(c == '+' || c == '-') return 1;
if(c == '*' || c == '/' || c == '%') return 2;
if(c == '^') return 3;
return -1;
}
// 判断是否为数字
bool isNumber(char c) {
return (c >= '0' && c <= '9') || c == '.';
}
// 中缀表达式转后缀表达式
string infixToPostfix(string infix) {
stack<char> s;
string postfix;
for(int i = 0; i < infix.length(); i++) {
if(isNumber(infix[i])) {
postfix += infix[i];
if(!isNumber(infix[i+1])) postfix += ' ';
}
else if(infix[i] == '(') {
s.push(infix[i]);
}
else if(infix[i] == ')') {
while(s.top() != '(') {
postfix += s.top();
postfix += ' ';
s.pop();
}
s.pop();
}
else {
while(!s.empty() && getPriority(s.top()) >= getPriority(infix[i])) {
postfix += s.top();
postfix += ' ';
s.pop();
}
s.push(infix[i]);
}
}
while(!s.empty()) {
postfix += s.top();
postfix += ' ';
s.pop();
}
return postfix;
}
// 后缀表达式计算
double calculate(string postfix) {
stack<double> s;
for(int i = 0; i < postfix.length(); i++) {
if(isNumber(postfix[i])) {
double num = 0, dec = 0, k = 1;
while(isNumber(postfix[i])) {
if(postfix[i] == '.') {
dec = 1;
i++;
continue;
}
if(dec == 0) {
num = num * 10 + (postfix[i] - '0');
}
else {
k *= 0.1;
num += (postfix[i] - '0') * k;
}
i++;
}
s.push(num);
i--;
}
else if(postfix[i] == '+') {
double num2 = s.top(); s.pop();
double num1 = s.top(); s.pop();
s.push(num1 + num2);
}
else if(postfix[i] == '-') {
double num2 = s.top(); s.pop();
double num1 = s.top(); s.pop();
s.push(num1 - num2);
}
else if(postfix[i] == '*') {
double num2 = s.top(); s.pop();
double num1 = s.top(); s.pop();
s.push(num1 * num2);
}
else if(postfix[i] == '/') {
double num2 = s.top(); s.pop();
double num1 = s.top(); s.pop();
if(num2 == 0) {
cout << "错误!除数不能为0。";
return 0;
}
s.push(num1 / num2);
}
else if(postfix[i] == '%') {
int num2 = s.top(); s.pop();
int num1 = s.top(); s.pop();
if(num2 == 0) {
cout << "错误!除数不能为0。";
return 0;
}
s.push(num1 % num2);
}
else if(postfix[i] == '^') {
double num2 = s.top(); s.pop();
double num1 = s.top(); s.pop();
s.push(pow(num1, num2));
}
else if(postfix[i] == 'u') {
double num = s.top(); s.pop();
s.push(-num);
}
}
return s.top();
}
// 主函数
int main() {
string infix;
cout << "输入中缀表达式:";
getline(cin, infix);
string postfix = infixToPostfix(infix);
cout << "后缀表达式:" << postfix << endl;
double result = calculate(postfix);
cout << "结果:" << result << endl;
return 0;
}
```
此代码使用了栈来实现中缀表达式转后缀表达式和后缀表达式计算。如果你还不熟悉栈的使用,建议先学习一下栈的相关知识。