Anyone knows how to create a runtime calculator using a C#?
Mitja Bonca 557 Nearly a Posting Maven
Here is my old calculator code:
PS: Add controls (buttons and textboxes on form - check which one are inside the code)
public partial class Form1 : Form
{
decimal num1, total;
int operation;
bool bNewCalc;
bool bNextNum;
public Form1()
{
InitializeComponent();
display.Text = string.Empty;
textBox1.Text = "0";
textBox1.TabStop = false;
Button[] btns = new Button[] { button0, button1, button2, button3, button4,
button5, button6, button7, button8, button9, };
foreach (Button btn in btns)
btn.Click += new EventHandler(Buttons_Click);
}
enum MathOperators
{
Multiplication = 0, // *
Division = 1, // /
Addition, // +
Subtraction // -
}
private void Buttons_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn != null)
{
if (bNextNum)
{
textBox1.Text = btn.Text;
bNextNum = false;
}
else
{
if (textBox1.Text.Equals("0") || bNewCalc)
{
textBox1.Text = btn.Text;
bNewCalc = false;
}
else
textBox1.Text += btn.Text;
}
num1 = int.Parse(textBox1.Text);
}
}
private void buttonMul_Click(object sender, EventArgs e)
{
SetOnOperation("*");
operation = (int)MathOperators.Multiplication;
}
private void buttonDiv_Click(object sender, EventArgs e)
{
SetOnOperation("/");
operation = (int)MathOperators.Division;
}
private void buttonAdd_Click(object sender, EventArgs e)
{
SetOnOperation("+");
operation = (int)MathOperators.Addition;
}
private void buttonMin_Click(object sender, EventArgs e)
{
SetOnOperation("-");
operation = (int)MathOperators.Subtraction;
}
private void SetOnOperation(string sign)
{
if (!bNextNum)
{
if (bNewCalc)
display.Text = String.Format("{0} {1}", total.ToString(), sign);
else
{
display.Text += String.Format("{0} {1} ", num1, sign);
bNextNum = true;
if (!total.Equals(0))
{
DoCalculation();
textBox1.Text = total.ToString();
}
else
total = decimal.Parse(textBox1.Text);
}
}
else
display.Text = String.Format("{0} {1} ", display.Text.Remove(display.Text.Length - 3, 3), sign);
}
private void buttonEquals_Click(object sender, EventArgs e)
{
DoCalculation();
textBox1.Text = total.ToString();
display.Text = string.Empty;
bNewCalc = true;
}
private void DoCalculation()
{
try
{
switch (operation)
{
case 0:
total = total * num1;
break;
case 1:
total = total / num1;
break;
case 2:
total = total + num1;
break;
case 3:
total = total - num1;
break;
}
}
catch
{
throw new DivideByZeroException();
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
textBox1.Text = "0";
display.Text = string.Empty;
bNextNum = false;
total = 0;
num1 = 0;
}
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.