c++写一个逐次加一法求优先函数的代码
时间: 2024-02-26 11:58:21 浏览: 36
下面是一个简单的 C++ 代码示例,用于实现逐次加一法求优先函数:
```c++
#include <iostream>
#include <string>
using namespace std;
// 判断字符是否为数字
bool isDigit(char ch) {
return ch >= '0' && ch <= '9';
}
// 判断字符是否为运算符
bool isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
// 根据优先级返回运算符的优先级,数字越大,优先级越高
int getPriority(char op) {
if (op == '*' || op == '/') {
return 2;
} else if (op == '+' || op == '-') {
return 1;
} else {
return 0;
}
}
// 逐次加一法求优先函数
void precedence(string input) {
int len = input.length();
int cur = 0;
char ch = input[cur++];
while (cur <= len) {
if (isDigit(ch)) {
cout << ch << " : " << 0 << endl;
ch = input[cur++];
} else if (isOperator(ch)) {
cout << ch << " : " << getPriority(ch) << endl;
ch = input[cur++];
} else {
// 处理非法字符
cout << ch << " : " << "invalid character" << endl;
ch = input[cur++];
}
}
}
int main() {
string input = "1+2*3/4-5";
precedence(input);
return 0;
}
```
在上面的代码中,我们定义了三个函数 isDigit、isOperator 和 getPriority,分别用于判断字符是否为数字、运算符以及返回运算符的优先级。然后,我们用 while 循环对输入的字符串进行逐个字符的处理,在处理过程中根据字符的类型输出相应的优先级。最后,我们在 main 函数中调用 precedence 函数,并传入一个测试用例 "1+2*3/4-5"。运行程序,输出以下结果:
```
1 : 0
+ : 1
2 : 0
* : 2
3 : 0
/ : 2
4 : 0
- : 1
5 : 0
```
这表明,我们的逐次加一法求优先函数的代码已经成功地将输入的字符串中的每个字符进行了处理,并输出了它的优先级。