【发布时间】:2013-05-23 23:19:04
【问题描述】:
由于某种原因,当我在这里测试我的“100-50-40”时,我得到的是“60”而不是“10”。所有其他组合都有效,例如“10+20”和“40-20”。当我尝试连续减去多个数字时会出现问题。有什么想法吗?
public double add(String exp){
String left = "";
String right = "";
double leftValue = 0;
double rightValue = 0;
double answer = 0;
for(int i=0;i<exp.length();i++)
{
if(exp.charAt(i)=='+')
{
right = exp.substring(i+1, exp.length());
leftValue = subtract(left);
rightValue = add(right);
answer = leftValue + rightValue;
return answer;
}
else
{
left = left + exp.substring(i,(i+1));
}
} // End for loop
answer = subtract(exp);
return answer;
} // End add method
//guaranteed there are no addition operators in exp
public double subtract(String exp){
String left = "";
String right = "";
double leftValue = 0;
double rightValue = 0;
double answer = 0;
for(int i=0;i<exp.length();i++)
{
if(exp.charAt(i)=='-')
{
right = exp.substring(i+1, exp.length());
leftValue = Double.parseDouble(left);
rightValue = subtract(right);
answer = leftValue - rightValue;
return answer;
}
else
{
left = left + exp.substring(i,(i+1));
}
} // End for loop
answer = Double.parseDouble(exp);
return answer;
}
【问题讨论】:
-
对不起,我是这个意思
-
我得到
90for100-50-40- 给定你的算法 - 似乎是预期值?!请注意,您的算法计算100-(50-40),而不是像人们预期的那样计算(100-50)-40。
标签: java methods add subtraction