C++ 函数解析:实现表达式计算
C++ 函数解析:实现表达式计算
这篇文章将解析一个 C++ 函数 fun,它可以计算给定数学表达式的结果。
#include <iostream>
#include <stack>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;
int fun(const string& expression)
{
stack<int> operands;
int i = 0, j = 0;
while (i < expression.size())
{
int flag = 0;
string num = '';
if (isdigit(expression[i])||(expression[i]=='-'&& isdigit(expression[i+1])))
{
if (expression[i] == '-')
{
flag = 1;
i++;
}
while (isdigit(expression[i]))
{
num += expression[i];
i++;
}
if (flag)
operands.push(-stoi(num));
else
operands.push(stoi(num));
}
else if (expression[i] != ',')
{
if (operands.size() < 2)
{
cout << '表达式不合法,缺少操作数。' << endl;
return 0;
}
int operand2 = operands.top();
operands.pop();
int operand1 = operands.top();
operands.pop();
switch (expression[i])
{
case '+':
operands.push(operand1 + operand2);
break;
case '-':
operands.push(operand1 - operand2);
break;
case '*':
operands.push(operand1 * operand2);
break;
case '/':
operands.push(operand1 / operand2);
break;
}
i++;
}
else
i++;
}
int result = operands.top();
operands.pop();
return result;
}
代码解释:
-
头文件:
<iostream>: 用于输入输出操作。<stack>: 用于使用堆栈数据结构。<vector>、<sstream>和<fstream>在此代码中未被使用,可以删除。
-
函数定义:
fun(const string& expression): 接受一个字符串类型的表达式作为参数,并返回一个整数结果。
-
变量声明:
stack<int> operands: 声明一个整数类型的堆栈operands,用于存储操作数。int i = 0, j = 0: 声明两个整数变量i和j,用于遍历表达式字符串,其中j未被使用。
-
循环遍历表达式:
while (i < expression.size()): 循环遍历表达式字符串的每个字符,直到字符串末尾。
-
处理数字:
if (isdigit(expression[i]) || (expression[i] == '-' && isdigit(expression[i + 1]))): 判断当前字符是否为数字或负数。- 如果是,则将连续的数字字符拼接成一个字符串
num,并将其转换为整数后压入operands堆栈中。
-
处理操作符:
else if (expression[i] != ','): 如果当前字符不是逗号,则认为是操作符。- 首先检查
operands堆栈中是否有足够的(至少两个)操作数。 - 如果操作数足够,则从堆栈中弹出两个操作数,并根据当前操作符执行相应的运算,并将结果压入
operands堆栈中。
-
返回结果:
- 循环结束后,
operands堆栈中应该只剩下一个元素,即最终的计算结果。将其弹出并返回作为函数的结果。
- 循环结束后,
示例:
对于表达式 '3,4,+,2,*,1,-', 该函数将返回 5。
总结:
该 fun 函数提供了一种简单有效的方式来计算字符串形式的数学表达式。它利用堆栈数据结构来处理操作符优先级,并提供基本的错误处理机制。
希望这篇博客能帮助你理解这个 C++ 函数的实现!
原文地址: https://www.cveoy.top/t/topic/bx26 著作权归作者所有。请勿转载和采集!