In the code I use an expression tree "3 + 2.53 - 1.75"
that should return a result of 3.78
. However, it ends up adding all the values within the string and outputs 7.28
. I ran through the code multiple times on paper trying to see what happens in each iteration of the for loop where the index variables i
and distance_operator
are used too. As far as I have gone through it I cannot find a reason why the program continues to add each float value. By the time the '-'
character is reached it should subtract the next value.
The distance_operator
is used to be an offset from the first operator where index i
will be pivoted so that I can take a portion of that string and calculate it using the substr() function.
float total = (float)value(expression[0]);
int distance_operator;
for (i = 1; i < expression.size(); i++) {
if (expression[i] == '+' || expression[i] == '-') {
distance_operator = i + 1;
while (expression[distance_operator] != '+' || expression[distance_operator] != '-') {
distance_operator++;
if (distance_operator == expression.size())
break;
}
if (expression[i] == '+')
total += std::stof(expression.substr(i, distance_operator - i));
else if(expression[i] == '-')
total -= std::stof(expression.substr(i, distance_operator - i));
}
}
The code is almost correct but there is an "off-by-one" error.
The problem is that when finding the -
the right substring used will be "- 1.75"
with a negative value when parsed as a number and you will be subtracting it, basically negating the value you wanted to use. The accumulating code should be:
if (expression[i] == '+')
total += std::stof(expression.substr(i+1, distance_operator-i-1));
else if(expression[i] == '-')
total -= std::stof(expression.substr(i+1, distance_operator-i-1));
Note that i+1
is used, so the expression sign found will be skipped.
Also note that this check
while (expression[distance_operator] != '+' || expression[distance_operator] != '-')
will always be true, because a thing is always different from A OR different from B. The correct logical operator is &&.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With