15,795,331 members
1.00/5 (1 vote)
See more:
I've been having difficulty fixing my equals function
Let's say I enter the operation 3 + 4, the result is 7 then 11 and so on. Working as intended same goes for multiplication.

However if I enter the operation 12 / 2 the result is 6 but when pressed again I receive 2 and pressing again gives 6, so obviously instead of calculating again I'm receiving the values of the next operation. This happens with subtraction as well.

Here's the following code:

```private void BtnCommonOperation_Clicked(object sender, System.EventArgs e)
{
var button = (Button)sender;
isOperatorClicked = true;
operatorName = button.Text;
firstNumber = Convert.ToDecimal(CalcResult.Text);
}

public decimal Calculate(decimal firstNumber, decimal secondNumber)
{
decimal result = 0;
if (operatorName == "+")
{
return firstNumber + secondNumber;
}
else if (operatorName == "-")
{
return firstNumber - secondNumber;
}
else if (operatorName == "*")
{
return firstNumber * secondNumber;
}
else if (operatorName == "/")
{
return firstNumber / secondNumber;
}
return result;
}

private void BtnEquals_Clicked(object sender, System.EventArgs e)
{

try
{
decimal secondNumber = Convert.ToDecimal(CalcResult.Text);
string finalResult = Calculate(firstNumber, secondNumber).ToString("");
CalcResult.Text = finalResult;

}
catch (Exception ex)
{
}
}
```

What I have tried:

I've tried inverting the order of firstNumber and secondNumber in the / and - operations and it seems to fix this issue, but will return me incorrect calculations of course for being out of order. If anyone can help me I'd be so happy.
Posted
Updated 21-Oct-22 16:42pm

## Solution 1

From what I can tell...

You put the first operand (X) in firstNumber.
Then you put the second operand (Y) in secondNumber.
Then you perform the operation, which is fine so far.
Then when you click Equal again, you are putting the result (X op Y) in secondNumber.
And calculating ( X op ( X op Y ) ), when you mean to be calculating ( ( X op Y ) op Y ) .

12 / 2 == 6
12 / 6 == 2
12 / 2 == 6
etc.

when you mean to do

12 / 2 == 6
6 / 2 == 3
3 / 2 == 1.5

You need `F(A,B)` such that each successive `F'(A,B)` is `F'(F(A,B),B)`

v2