C# Calculator - The Equals Button

<< Continues from the previous section

The Equals button is where the action takes place. This is where we will do the actual addition.

To store the answer to the addition, we'll need another variable (in blue bold below):

double total1 = 0;

double total2 = 0;

private void btnPlus_Click(object sender, EventArgs e)
{

total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();

}

So set up a total2 variable in your code, as we've done above.

total2 = total1 + double.Parse( txtDisplay.Text );
txtDisplay.Text = total2.ToString( );
total1 = 0;

The first line should look familiar:

total2 = total1 + double.Parse( txtDisplay.Text );

To the right of the equals sign, we're doing the same thing as before:

total1 + double.Parse(txtDisplay.Text);

The difference is before the equals sign: we're now storing it in the total2 variable:

total2 = total1 + double.Parse(txtDisplay.Text);

In other words, get the number from the text box, convert it to a double variable, add it to whatever is in total1. When all this is worked out, store the answer in the variable called total2.

txtDisplay.Text = total2.ToString( );

On the right of the equals sign, we're converting the total2 variable To a String. This is so that it can be displayed as Text in the text box.

The third line of code resets the total1 variable to zero:

total1 = 0;

This is so a new sum can be calculated.

Time to try out your calculator. Use it to calculate the following:

10 + 25
36 + 36
10 + 10 + 10

Of course, you can do these sums in your head. But make sure that your calculator gets its sums right before going any further. Click your Clear button to start a new addition. When you're sure you understand what is going on with the code, try this exercise.

Exercise C
You have not yet written any code for the btnPoint button. This means that you can't have numbers like 10.5 or 36.7 in your additions. Write code to solve this. (Hint: you only need one line of code.)