Introduction
I created this application in response to this question about how to implement a simple calculator.
Using the Code
using System;
using System.Windows.Forms;
namespace RedCell.App.Calculator.Example
{
public partial class Form1 : Form
{
private double accumulator = 0;
private char lastOperation;
public Form1()
{
InitializeComponent();
}
private void Operator_Pressed(object sender, EventArgs e)
{
char operation = (sender as Button).Text[0];
if (operation == 'C')
{
accumulator = 0;
}
else
{
double currentValue = double.Parse(Display.Text);
switch (lastOperation)
{
case '+': accumulator += currentValue; break;
case '-': accumulator -= currentValue; break;
case '×': accumulator *= currentValue; break;
case '÷': accumulator /= currentValue; break;
default: accumulator = currentValue; break;
}
}
lastOperation = operation;
Display.Text = operation == '=' ? accumulator.ToString() : "0";
}
private void Number_Pressed(object sender, EventArgs e)
{
string number = (sender as Button).Text;
Display.Text = Display.Text == "0" ? number : Display.Text + number;
}
}
}
The way it works is simple.
- There are two kinds of buttons, numbers and operators.
- There is a display that shows entries and results.
- There is an
accumulator
variable to store the accumulated value. - There is a
lastOperation
variable to store the last operator, because we won't evaluate until another operator is pressed.
When a number is pressed, it is added to the end of the number currently on the display. If a 0
was on the display we replace it, just to look nicer.
If the C
operator is pressed, we reset the accumulator
to 0
.
Otherwise we perform the last operation against the accumulator and the currently entered number. If there wasn't a lastOperation
, then we must be starting a new calculation, so we set the accumulator
to the currentValue
as the first operation.
Points of Interest
Trying to emulate a basic calculator can be a good exercise for a new programmer. I created this application in 15 minutes to demonstrate that it does not need to be complicated.
C# is somewhat verbose. What could you do to use less code? Calculators these days are pretty smart, but back in the olden days when I started programming for embedded systems it would be common to only have 100 bytes or less of memory in which the program was stored, so writing the code (in machine language) to be as small as possible was important.
Back to work...
History
- December 14, 2014 - Wrote this