gpt4 book ai didi

java - 评估代码,区分负数和负数?

转载 作者:太空宇宙 更新时间:2023-11-04 13:20:02 29 4
gpt4 key购买 nike

我正在计算一个表达式,但在输入负数时遇到了麻烦。由于我的代码的结构,以及减法运算符和负号是同一字符的事实,我的代码不适用于负数。有办法解决这个问题吗?

private float evalNoPB(String s) {

float tempAns = 0;
if (s.contains("*") == false && s.contains("/") == false && s.contains("+") == false && s.contains("-") == false) {
return Float.parseFloat(s);
}

if (s.length() - 1 > 0) {
int i;
boolean foundPlusMinus = false;
for (i = s.length() - 1; i > 0; i--) {
if (s.charAt(i) == '+' || s.charAt(i) == '-') {
System.out.println(i);
foundPlusMinus = true;
break; // keep value of i for substrings
}
foundPlusMinus = false;
}

if (foundPlusMinus == false) { // for loop went through and did not find + or -
for (i = s.length() - 1; i > 0; i--) {
if (s.charAt(i) == '*' || s.charAt(i) == '/') {
System.out.println(i);
break; // keep value of i for substrings
}
}
}

String sub1 = s.substring(0, i);
System.out.println(sub1);
String sub2 = s.substring(i + 1, s.length());
System.out.println(sub2);

if (s.charAt(i) == '+') {
tempAns = evalNoPB(sub1) + evalNoPB(sub2);
} else if (s.charAt(i) == '-') {
tempAns = evalNoPB(sub1) - evalNoPB(sub2);
} else if (s.charAt(i) == '*') {
tempAns = evalNoPB(sub1) * evalNoPB(sub2);
} else if (s.charAt(i) == '/') {
float divisorCheck = evalNoPB(sub2);
if (divisorCheck != 0) {
tempAns = evalNoPB(sub1) / evalNoPB(sub2);
} else { // cannot divide by 0
throw new IllegalArgumentException("cannot divide by 0");
}
}
}
return tempAns;

}

最佳答案

一种解决方法是永远不要“减”,只需添加负数(如果需要减去某些内容,请将其乘以 -1 并与另一个数字相加)。

伪代码:

if I come across a - with nothing on either side and not first in string {
add a + to the left of it
}
else {
if first in string {
add 1* to left of it
}
do stuff that has to do with *, /, or +.
}
if i run across a + {
check to see if - is to right of it
if so {
add together the values but with the value to right of - multiplied by -1
}
else {
add together values
}
}

关于java - 评估代码,区分负数和负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33158960/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com