(个人水平有限,请见谅!)
描述:
实现一个算法,可以进行任意非负整数的加减乘除组合四则运算。
请注意运算符的优先级。
输入:
请输入一行算式,使用空格分隔数字与运算符。
数字为任意非负整数,运算符为+ - * /,不考虑括号。
输出:
输出算式的运算结果。如果是小数,请向下取整(包含中间步骤结果)。 如果出现“除0异常”,输出err。
输入样例:
3 + 5
12 + 45 / 9
1 / 2
1 / 0
12 + 34 * 56 - 78
输出样例:
8
17
0
err
1838
代码示例:
#include <iostream>
#include <bits/stdc++.h>
#include <string>
#include <vector>
#include <string.h>
using namespace std;
int main()
{
char line[1000001];
// 循环读入多行数据
while (cin.getline(line, 1000000)) {
vector <string> eqution;
char cstr[10];
string str, temp_s;
int temp, temp1, temp2;
int flag = 0;
char *p = strtok(line, " ");
while (p)
{
sscanf(p, "%s", cstr);
str = cstr;
eqution.push_back(str);
p = strtok(NULL, " ");
}
for (int i = 1; i < eqution.size(); )
{
if (eqution[i] == "*" && flag == 0)
{
temp1 = atoi(eqution[i - 1].c_str());
temp2 = atoi(eqution[i + 1].c_str());
temp = temp1 * temp2;
temp_s = to_string(temp);
eqution.insert(eqution.begin() + i - 1, temp_s);
eqution.erase(eqution.begin() + i);
eqution.erase(eqution.begin() + i);
eqution.erase(eqution.begin() + i);
}
else if (eqution[i] == "/" && flag == 0)
{
temp1 = atoi(eqution[i - 1].c_str());
temp2 = atoi(eqution[i + 1].c_str());
if (temp2 == 0)
{
flag = 1;
break;
}
temp = temp1 / temp2;
temp_s = to_string(temp);
eqution.insert(eqution.begin() + i - 1, temp_s);
eqution.erase(eqution.begin() + i);
eqution.erase(eqution.begin() + i);
eqution.erase(eqution.begin() + i);
}
else
i = i + 2;
}
for (int i = 1; i < eqution.size(); )
{
if (eqution[i] == "+" && flag == 0)
{
temp1 = atoi(eqution[i - 1].c_str());
temp2 = atoi(eqution[i + 1].c_str());
temp = temp1 + temp2;
temp_s = to_string(temp);
eqution.insert(eqution.begin() + i - 1, temp_s);
eqution.erase(eqution.begin() + i);
eqution.erase(eqution.begin() + i);
eqution.erase(eqution.begin() + i);
}
else if (eqution[i] == "-" && flag == 0)
{
temp1 = atoi(eqution[i - 1].c_str());
temp2 = atoi(eqution[i + 1].c_str());
temp = temp1 - temp2;
temp_s = to_string(temp);
eqution.insert(eqution.begin() + i - 1, temp_s);
eqution.erase(eqution.begin() + i);
eqution.erase(eqution.begin() + i);
eqution.erase(eqution.begin() + i);
}
else
i = i + 2;
}
if (flag == 0)
cout << eqution[0] << endl;
else
cout << "err" << endl;;
}
return 0;
}