2021.06.02会解方程的计算器
(题目来源:)
题目描述
为了很好的完成这个任务,ZL先生首先研究了一些一元一次方程的实例:
4+3x=8
6a-5+1=2-2a
-5+12y=0
ZL先生被主管告之,在计算器上键入的一个一元一次方程中,只包含整数、小写字母及+、-、=这三个数学符号(当然,符号“-”既可作减号,也可作负号)。方程中并没有括号,也没有除号,方程中的字母表示未知数。
你可假设对键入的方程的正确性的判断是由另一个程序员在做,或者说可认为键入的一元一次方程均为合法的,且有唯一实数解。
输入格式
一个一元一次方程。
输出格式
解方程的结果(精确至小数点后三位)。
样例输入
6a-5+1=2-2a
样例输出
a=0.750
思路
模拟题,talk is cheap, show u the code.
代码
class Solution{
void test() {
Scanner cin = new Scanner(System.in);
String fun = cin.nextLine();
String[] strs = fun.split("=");
String left = strs[0];
String right = strs[1];
if(left.charAt(0) != '+' && left.charAt(0) != '-') left = '+'+left;
if(right.charAt(0) != '+' && right.charAt(0) != '-') right = '+'+right;
int lasInd = -1;
List<num> leftNums = new ArrayList<num>(); //左边所有项
lasInd = 0;
for(int i = 0; i < left.length(); i++) {
if((left.charAt(i) == '+' || left.charAt(i) == '-') && i != 0) {
leftNums.add(new num(left.substring(lasInd,i)));
lasInd = i;
}
}
leftNums.add(new num(left.substring(lasInd)));
List<num> rightNums = new ArrayList<num>(); //右边所有项
lasInd = 0;
for(int i = 0; i < right.length(); i++) {
if((right.charAt(i) == '+' || right.charAt(i) == '-') && i != 0) {
rightNums.add(new num(right.substring(lasInd,i)));
lasInd = i;
}
}
rightNums.add(new num(right.substring(lasInd)));
int t = 0; //合并后的系数
int c = 0;
for(num x: leftNums) {
if(x.above0) {
if(x.isX) t += x.times;
else c += x.n;
} else {
if(x.isX) t -= x.times;
else c -= x.n;
}
}
for(num x: rightNums) {
if(x.above0) {
if(x.isX) t -= x.times;
else c -= x.n;
} else {
if(x.isX) t += x.times;
else c += x.n;
}
}
double C = c*(-1);
double T = t;
char ch = 'x';
for(int i = 0; i < fun.length(); i++) if(fun.charAt(i)>='a'&&fun.charAt(i)<='z') {
ch = fun.charAt(i);
break;
}
if(c==0) System.out.println("0.000"); //由于浮点数表示时会显示"-0.000"
else System.out.printf(ch+"=%.3f",C/T);
}
}
class num{
int n;
boolean isX = false;
boolean above0;
int times;
char ch;
num(String arg){
//判断正负
if(arg.charAt(0) == '+')above0 = true;
else above0 = false;
//判断是否有未知数
int ind = -1;
for(int i = 0; i < arg.length(); i++) {
if(arg.charAt(i)>='a' && arg.charAt(i)<='z') {
ind = i;
ch = arg.charAt(i);
isX = true;
break;
}
}
if(isX) { //如果有未知数,找到系数
StringBuilder sb = new StringBuilder();
for(int i = 1; i < ind; i++) {
sb.append(arg.charAt(i));
}
if(sb.length()==0) times = 1;
else times = Integer.parseInt(sb.toString());
} else { //如果没有未知数,找到数值大小
n = Integer.parseInt(arg.substring(1));
}
}
@Override
public String toString() {
if(isX) {
return "有未知数:"+(above0?"+":"-")+times+"x";
} else {
return (above0?"+":"-")+n;
}
}
}
1204

被折叠的 条评论
为什么被折叠?



