-
Calculator help
Just need a point in the right direction
So I'm making this calculator, that deals with multiple calculations in one go.
expected input(currently only done + and *)
2 + 5 X 2; This should be 12(5*2 = 10 + 2 = 12);
Output:
20
Calc code:
Code:
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
a.AddRange(tb.Text.Split('+'));
double ret=0;
for (int i=0; i < a.Count; i++)
{
if (a[i].ToString().Contains('X'))
{
b.AddRange(a[i].ToString().Split('X'));
ret = 0;
foreach (string s in b)
{
if (ret == 0)
{
ret = double.Parse(s);
}
else
{
ret = ret * double.Parse(s);
}
}
a.Add(ret.ToString());
}
if (!a[i].ToString().Contains('X'))
{
ret = ret + double.Parse(a[i].ToString());
}
}
return ret;
So any pointers in what I'm doing wrong?
-
Re: Calculator help
Ok. Well, there are several things wrong with this.... However, the reason you are getting your wrong answer is because in the first iteration of your loop... you assign the number 2 to the "RET" variable.
Then the second iteration you parse out the 5X2... figure the result then assign that back to your "A" Array List. Now you have two problems....
1. You've added another element to your array list so you are going to loop again. and the a[i] will contain the value of 10.
2. Because in your 2nd pass, you assigned the value of 2*5 to the variable "RET", that just overwrote the previous value of 2.
So, in your final loop iteration you are performing this code
Code:
if (!a[i].ToString().Contains('X'))
{
ret = ret + double.Parse(a[i].ToString());
}
so what is happening is you are doing this.... ret = 10 + 10 instead of ret = 2 + 10