计算器的改良
题目链接:链接: https://www.luogu.com.cn/problem/P1022.
本题是解一元一次方程,例如
输入:6a-5+1=2-2a
输出:a=0.750
思路:记录下未知数、符号(正负)、等号和系数,记录是数字的字符串,当遇到未知数、符号(正负)、等号和系数时就进行计算,当遍历到最后时会有一个数剩下,最后加上就好了。
开始时等号记为1,当遍历到等号时,就把等号记为-1,就相当于把等号右边的式子移到左边来计算,
例如6a-5+1=2-2a 变成 6a-5+1 - 2 - 2a = 0;
#include <iostream>
#include<iomanip>
using namespace std;
#include <string>
#include <cmath>
void calculation(string str)
{
int n = str.size();
int equalSign = 1,sign = 1,coe = 0;//coe是系数
char unkonwNum;
int num = 0,sum = 0;
for (int i = 0; i < n; i++) {
if (isdigit(str[i])) {
num = num * 10 + str[i] - '0';
}else if(str[i] >= 'a' && str[i] <= 'z'){
unkonwNum = str[i];
if ((i>0 && !isdigit(str[i - 1])) || (i == 0 && !isdigit(str[i]))) {
coe += equalSign * sign;
}else{
coe += equalSign * sign * num;
num = 0;
}
}else if(str[i] == '+'){
sum += equalSign * sign * num;
sign = 1;
num = 0;
}else if(str[i] == '-'){
sum += equalSign * sign * num;
sign = -1;
num = 0;
}else if(str[i] == '='){
sum += sign * num;
num = 0;
equalSign = -1;
sign = 1;//因为原来记录的是等号左边的符号,所以要变回来
}
}
sum += equalSign * sign * num;
double ans = (double)(-sum) / coe;
ans = ans == 0 ? abs(ans) : ans;//防止出现-0
cout<< unkonwNum << "=" << setiosflags(ios::fixed) << setprecision(3) << ans << endl;
}
int main()
{
string str;
cin >> str;
calculation(str);
return 0;
}