Calculator Trouble: Only getting second value I enter - c#

I created a basic calculator, but each time I enter the second value and press the equal button, I get no result back. Only the value I entered 2nd.
My methods for +-*/ are in a separate class. What will the best way be to resolve this problem? It is probably a simple error, but I can't find it. Can you also please give me an explanation on what I did wrong. Thanks in Advance.
public sealed partial class Calculator : Page
{
public double num01, num02;
int operater;
public Calculator()
{
this.InitializeComponent();
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text =txtcalcdisplay.Text+ "1";
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "2";
}
private void btn3_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "3";
}
private void btn4_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "4";
}
private void btn5_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "5";
}
private void btn6_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "6";
}
private void btn7_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "7";
}
private void btn8_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "8";
}
private void btn9_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = txtcalcdisplay.Text + "9";
}
private void Clear_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text = string.Empty;
}
private void btnsubtract_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '1';
}
private void btnadd_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '2';
}
private void btnmultiply_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '3';
}
private void btndivide_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = '4';
}
private void btnequals_Click(object sender, RoutedEventArgs e)
{
switch (operater)
{
case 1:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass sub = new CalculationClass();
double answer= sub.Subtract(num01, num02);
txtcalcdisplay.Text = answer.ToString();
break;
case 2:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass add = new CalculationClass();
answer= add.Addition(num01, num02);
txtcalcdisplay.Text = answer.ToString();
break;
case 3:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass mult = new CalculationClass();
answer = mult.Multiply(num01, num02);
txtcalcdisplay.Text = answer.ToString();
break;
case 4:
num02 = Convert.ToDouble(txtcalcdisplay.Text);
CalculationClass div = new CalculationClass();
answer = div.Div(num01, num02);
txtcalcdisplay.Text = Convert.ToString(answer);
break;
}
}
private void btnback_Click(object sender, RoutedEventArgs e)
{
}
private void btnplusdivideminus_Click(object sender, RoutedEventArgs e)
{
}
private void btncomma_Click(object sender, RoutedEventArgs e)
{
}
private void btngallery_Click(object sender, RoutedEventArgs e)
{
}
private void btncontact_Click(object sender, RoutedEventArgs e)
{
}
private void num0_Click(object sender, RoutedEventArgs e)
{
txtcalcdisplay.Text += "0";
num01 = Convert.ToDouble(txtcalcdisplay.Text);
}
}
class CalculationClass
{
double answer;
public double Addition(double x, double y)
{
answer = x + y;
return answer;
}
public double Subtract(double x, double y)
{
answer = x - y;
return answer;
}
public double Multiply(double x, double y)
{
answer = x * y;
return answer;
}
public double Div(double x, double y)
{
answer = x / y;
return answer;
}
}

I'm not 100% certain, but I'm fairly sure this has to do with the fact that your variable operater is an int but you're assigning a character to it (this works - characters can be assigned to ints) and then comparing it back to the integer (eg doing 1 == '1')
int x = '1';
Console.WriteLine(x); // outputs 49
Console.WriteLine(x == 1); // outputs false
So to fix it either use the characters in your switch:
switch(operater){
case '1': ...
}
Or assign the integer 1,2,3,4 rather than the character '1','2,'3','4'
private void btnadd_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = 2; // here
}

So in your operator click handlers (the ones for +,-,*,/ etc.) you are setting your operater variable to a character '1','2', etc. Well, your operater variable is an int. But wait, you shouldn't be able to assign a char to an int?! Well, the compiler does an implicit conversion here (language spec says it should).
So what ends up happening when you do operater = '1' is that operater gets assigned 49 ('1''s ASCII value). Then when you get to your equals button click handler it hits that switch statement. And guess what? You don't have a case for 49. So nothing happens and you keep seeing your second number as the text on screen.
So to fix it, remove the single quotes around your numbers you assign to operater in your operator handlers. IE:
private void btnsubtract_Click(object sender, RoutedEventArgs e)
{
num01 = Convert.ToDouble(txtcalcdisplay.Text);
txtcalcdisplay.Text = "";
operater = 1; // <-- change this line to be like this, removed the single quotes
}

Related

Trying to minus 2 values together results in them adding instead, also all operators exept addition do not function

For some reason when I test the code the minus if statement adds the two values togehther instead of minusing them, along with that the other if statements for times and subtraction return the error message
System.FormatException: 'Input string was not in a correct format.'
The first if statement for addition works fine despite this
public Form1()
{
InitializeComponent();
}
private void Calculation()
{
decimal answer;
if (savedOperator == "+")
{
answer = savedNumber + Convert.ToDecimal(txtBox.Text);
txtBox.Text = answer.ToString();
savedOperator = "";
}
if (savedOperator == "-")
{
answer = savedNumber - Convert.ToDecimal(txtBox.Text);
txtBox.Text = answer.ToString();
savedOperator = "";
}
if (savedOperator == "*")
{
answer = savedNumber * Convert.ToDecimal(txtBox.Text);
txtBox.Text = answer.ToString();
savedOperator = "";
}
if (savedOperator == "/")
{
answer = savedNumber / Convert.ToDecimal(txtBox.Text);
txtBox.Text = answer.ToString();
savedOperator = "";
}
}
private void SaveNumber()
{
savedNumber = System.Convert.ToDecimal(txtBox.Text);
txtUpperBox.Text = savedNumber.ToString();
}
// numbers
private void btn1_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "1";
}
private void btn2_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "2";
}
private void btn3_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "3";
}
private void btn4_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "4";
}
private void btn5_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "5";
}
private void btn6_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "6";
}
private void btn7_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "7";
}
private void btn8_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "8";
}
private void btn9_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "9";
}
private void btn0_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + "0";
}
// operators
private void btnPlus_Click(object sender, EventArgs e)
{
SaveNumber();
txtBox.Clear();
savedOperator = "+";
txtBox.Text = "+";
}
private void btnMinus_Click(object sender, EventArgs e)
{
SaveNumber();
txtBox.Clear();
savedOperator = "-";
txtBox.Text = "-";
}
private void btnTimes_Click(object sender, EventArgs e)
{
SaveNumber();
txtBox.Clear();
savedOperator = "*";
txtBox.Text = "*";
}
private void btnDivide_Click(object sender, EventArgs e)
{
SaveNumber();
txtBox.Clear();
savedOperator = "/";
txtBox.Text = "/";
}
private void btnEquals_Click(object sender, EventArgs e)
{
Calculation();
}
}
}
I don't see any obvious problems in your math logic.
I tested it in https://dotnetfiddle.net/Uo2EHM and it works fine. The issue could be in the inputs you are getting or in conversion.
You can either set breakpoints at various points in your code to see what the values are or print out the values to another "debug" text box.
Some potential issues I see are in conversion between number and string. Sometimes, it may not give you the results you expect.
Also, you might want to use a switch statement instead of multiple if statements but that is not a bug you are seeing.
Could the issue be with the value of the TextBox before the calculations are performed? If you have "8--3" it would be the same as 8 - (-3). Try your code with different text boxes for the numbers and the operators to see if the problem occurs.

Making values to perform addition in a single textbox

I recently got stuck in my project as I have requirements that I need to fulfil, the need to perform addition in a single textbox.
I've view the most similar posts and it gave a good idea of it, Addition using a single TextBox.
Instead of int, I am required to use double like how it was done with int.
private int i = 0;
private int[] a = new int[2];
private void button1_Click(object sender, EventArgs e)
{
int b;
if(Int32.TryParse(textBox1.Text, out b))
{
a[i] = b;
i++;
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
int sum = a[0] + a[1];
MessageBox.Show("Sum: " + sum);
}
}
Instead, what code should I use to create a similar things for double?
If you want to keep your code, just do this :
private int i = 0;
private double[] a = new double[2];
private void button1_Click(object sender, EventArgs e)
{
double b;
if (Double.TryParse(textBox1.Text, out b))
{
a[i] = b;
i++;
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
double sum = a[0] + a[1];
MessageBox.Show("Sum: " + sum);
}
But you can try this for adding more than 2 doubles :
private double result = 0.0;
private void button1_Click(object sender, EventArgs e)
{
double b;
if (Double.TryParse(textBox1.Text, out b))
{
result += b,
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
MessageBox.Show("Sum: " + result);
}
double b = 0;
try{
b = Convert.ToDouble(textBox1.Text);
}
catch(e){
// Error Handling
}
Docs: https://learn.microsoft.com/en-us/previous-versions/windows/apps/zh1hkw6k(v=vs.105)
you can try use something like:
Double.Parse("1.2");
some examples here:
https://msdn.microsoft.com/en-us/library/fd84bdyt(v=vs.110).aspx

Operator is part of the calculation string for calculator

I am making a calculator in c#. the equation by the user is displayed in a textbox called textBoxInput and the result is displayed in labelResult. When I hit the 'equals' button a System.FormatException Exception occurs at secondInt = int.Parse(textBoxInput.Text); which to me means that the program is trying to convert the operator into an int aswell as the integers input by the user in textBoxInput. My question is how can I make the program just convert the first and secondInts's without trying to convert the operator aswell? I want to keep the entire equation in textBoxInput while the result is displayed in labelResult. Here is the enitre code for the calculator class which the problem exists in.
public partial class Calculator : Form
{
int firstInt;
int secondInt;
int result;
string Operator;
Boolean Op;
public Calculator()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBoxInput.Text += ("1");
}
private void button2_Click(object sender, EventArgs e)
{
textBoxInput.Text += ("2");
}
private void button3_Click(object sender, EventArgs e)
{
textBoxInput.Text += ("3");
}
private void button4_Click(object sender, EventArgs e)
{
textBoxInput.Text += ("4");
}
private void button5_Click(object sender, EventArgs e)
{
textBoxInput.Text += ("5");
}
private void button6_Click(object sender, EventArgs e)
{
textBoxInput.Text += ("6");
}
private void button7_Click(object sender, EventArgs e)
{
textBoxInput.Text += ("7");
}
private void button8_Click(object sender, EventArgs e)
{
textBoxInput.Text += ("8");
}
private void button9_Click(object sender, EventArgs e)
{
textBoxInput.Text += ("9");
}
private void button10_Click(object sender, EventArgs e)
{
textBoxInput.Text += ("0");
}
private void labelResult_Click(object sender, EventArgs e)
{
}
private void buttonEquals_Click(object sender, EventArgs e)
{
Calculations application = new Calculations();
secondInt = int.Parse(textBoxInput.Text);
switch (Operator)
{
case "/":
result = application.Division(firstInt, secondInt);
labelResult.Text = (firstInt + " / " + secondInt + "\n" + "= " + result);
break;
case "+":
result = application.Addition(firstInt, secondInt);
labelResult.Text = (firstInt + " + " + secondInt + "\n" + "= " + result);
break;
case "-":
result = application.Subtract(firstInt, secondInt);
labelResult.Text = (firstInt + " - " + secondInt + "\n" + "= " + result);
break;
case "*":
result = application.Multiply(firstInt, secondInt);
labelResult.Text = (firstInt + " * " + secondInt + "\n" + "= " + result);
break;
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
firstInt = int.Parse(textBoxInput.Text);
textBoxInput.Text += (" + ");
Op = true;
Operator = "+";
}
private void buttonClear_Click(object sender, EventArgs e)
{
textBoxInput.Text = "";
labelResult.Text = "";
}
private void buttonMultiply_Click(object sender, EventArgs e)
{
firstInt = Convert.ToInt32(textBoxInput.Text);
Operator = "*";
textBoxInput.Text += (" * ");
}
private void buttonSubtract_Click(object sender, EventArgs e)
{
firstInt = Convert.ToInt32(textBoxInput.Text);
Operator = "-";
textBoxInput.Text += (" - ");
}
private void button12_Click(object sender, EventArgs e)
{
firstInt = Convert.ToInt32(textBoxInput.Text);
Operator = "/";
textBoxInput.Text += (" / ");
}
private void button10_Click_1(object sender, EventArgs e)
{
textBoxInput.Text += (".");
}
}
}
Basically, you can't use int.Parse by itself here. You are going to need to do a character-by-character inspection of the code and decide for yourself whether each piece is part of a value vs an operator - essentially building an AST. Then compute the AST using whichever precedence rules your calculator implements.
Try changing this line:
secondInt = int.Parse(textBoxInput.Text);
to this:
secondInt = int.Parse(textBoxInput.Text.Split('/', '+', '-', '*')[1].Trim());
And see if it helps.
I tried to simply answer the question, not delve into details of making a solid calculator application since the topic is too broad.
You can use Mathematical Expressions Evaluator for .NET e.g: NCalc
Expression e = new Expression("2 + 3 * 5");
Debug.Assert(17 == e.Evaluate());
For your case
Expression e = new Expression(textBoxInput.Text);
labelResult.Text = e.Evaluate().ToString();

windows forms input continuously showing

I cannot for the life of me figure out how to continuously show the input and then output of the numbers for this.
What do you do to store the numbers somewhere and then show them? I've gone in so many circles that I have confused myself to oblivion.
I know what needs to be done but not how or exactly where to do it?
public partial class Form1 : Form
{
char c;
double num1;
double num2;
public Form1()
{
InitializeComponent();
}
private void btn0_Click(object sender, EventArgs e)
{
txtBox.Text += 0;
}
private void btn1_Click(object sender, EventArgs e)
{
txtBox.Text += 1;
}
private void btn2_Click(object sender, EventArgs e)
{
txtBox.Text += 2;
}
private void btn3_Click(object sender, EventArgs e)
{
txtBox.Text += 3;
}
private void btn4_Click(object sender, EventArgs e)
{
txtBox.Text += 4;
}
private void btn5_Click(object sender, EventArgs e)
{
txtBox.Text += 5;
}
private void btn6_Click(object sender, EventArgs e)
{
txtBox.Text += 6;
}
private void btn7_Click(object sender, EventArgs e)
{
txtBox.Text += 7;
}
private void btn8_Click(object sender, EventArgs e)
{
txtBox.Text += 8;
}
private void btn9_Click(object sender, EventArgs e)
{
txtBox.Text += 9;
}
private void btnDecimal_Click(object sender, EventArgs e)
{
if (!txtBox.Text.Contains('.'))
txtBox.Text += '.';
}
private void btnAddition_Click(object sender, EventArgs e)
{
c = '+';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnSubtraction_Click(object sender, EventArgs e)
{
c = '-';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnMultiplication_Click(object sender, EventArgs e)
{
c = '*';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnDivision_Click(object sender, EventArgs e)
{
c = '/';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBox.Clear();
}
private void btnEqual_Click(object sender, EventArgs e)
{
num2 = double.Parse(txtBox.Text);
double result;
switch (c)
{
case '+':
result = num1 + num2;
txtBox.Text = result.ToString();
break;
case '-':
result = num1 - num2;
txtBox.Text = result.ToString();
break;
case '/':
if (num2 != 0)
{
result = num1 / num2;
txtBox.Text = result.ToString();
}
else
{
txtBox.Text = "You can't divide by zero... sign up for Math 100 please =)";
}
break;
case '*':
result = num1 * num2;
txtBox.Text = result.ToString();
break;
}
}
}
}
I'll let you wire this up, but here is what I threw together.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private string op;
private string num1;
private string num2;
private void handleNumberButtonClick(object sender, System.EventArgs e)
{
var num = Convert.ToInt16(((Button)sender).Tag);
if (op == null)
num1 += num;
else
num2 += num;
PrintEquation(num1, op, num2);
}
private void PrintEquation(string first, string oper = null, string second = null, string equals = null, string result = null)
{
txtBox.Text = first + oper + second + equals + result;
}
private void handleOperatorButtonClick(object sender, System.EventArgs e)
{
op = ((Button)sender).Tag.ToString();
PrintEquation(num1, op);
}
private void btnDecimal_Click(object sender, EventArgs e)
{
if (op == null && !num1.Contains(".")) num1 += ".";
if (op != null && !num2.Contains(".")) num2 += ".";
this.PrintEquation(num1, op, num2);
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBox.Clear();
op = null;
num1 = null;
num2 = null;
}
private void btnEqual_Click(object sender, EventArgs e)
{
double result = 0;
var first = Convert.ToDouble(num1);
var second = Convert.ToDouble(num2);
switch (op)
{
case "+":
result = first + second;
break;
case "-":
result = first - second;
break;
case "/":
if (second != 0)
{
result = first / second;
}
else
{
errorLbl.Text = "You can't divide by zero... sign up for Math 100 please =)";
}
break;
case "*":
result = first * second;
break;
}
this.PrintEquation(num1, op, num2, "=", result.ToString());
}
}
To give you a clue on how things go together, this is what the button should look like in the .designer.cs file:
this.btn0.Location = new System.Drawing.Point(12, 60);
this.btn0.Name = "btn0";
this.btn0.Size = new System.Drawing.Size(75, 23);
this.btn0.TabIndex = 1;
this.btn0.Tag = "0";
this.btn0.Text = "btn0";
this.btn0.UseVisualStyleBackColor = true;
this.btn0.Click += new System.EventHandler(this.handleNumberButtonClick);
Notice the .Tag value and the eventhandler.
The Operators should look like this(this is add, notice the tag and the Click Event handler):
this.addButton.Location = new System.Drawing.Point(178, 60);
this.addButton.Name = "addButton";
this.addButton.Size = new System.Drawing.Size(75, 23);
this.addButton.TabIndex = 11;
this.addButton.Tag = "+";
this.addButton.Text = "add";
this.addButton.UseVisualStyleBackColor = true;
this.addButton.Click += new System.EventHandler(this.handleOperatorButtonClick);
And the decimal, like this:
this.button4.Location = new System.Drawing.Point(178, 176);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 23);
this.button4.TabIndex = 15;
this.button4.Tag = ".";
this.button4.Text = "decimal";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.btnDecimal_Click);
Oh, and throw this in your clear button definition
this.button5.Click += new System.EventHandler(this.btnClear_Click);
Special thanks to #Mark Hall and #Martin James for their insights

C# Calculator working incorrectly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The calculator works fine if I keep using the same operator(*, /, +, -) but if for example I decide to multiply the total of two added numbers it'll give me a wrong answer. I've looked for a solution but can't seem to find one.
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
bool multiply = false;
bool divide = false;
bool add = false;
bool subtract = false;
private void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "1";
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "2";
}
private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "3";
}
private void btnFour_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "4";
}
private void btnFive_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "5";
}
private void btnSix_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "6";
}
private void btnSeven_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "7";
}
private void btnEight_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "8";
}
private void btnNine_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + "9";
}
private void btnZero_Click(object sender, EventArgs e)
{
if (txtDisplay.Text.Length > 0)
{
txtDisplay.Text = txtDisplay.Text + "0";
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Clear();
}
private void btnDecimalPoint_Click(object sender, EventArgs e)
{
if (txtDisplay.Text.Contains("."))
{
return;
}
else
{
txtDisplay.Text = txtDisplay.Text + ".";
}
}
private void btnNegative_Click(object sender, EventArgs e)
{
if (txtDisplay.Text.Contains("-"))
{
txtDisplay.Text = txtDisplay.Text.Remove(0,1);
}
else
{
txtDisplay.Text = "-" + txtDisplay.Text;
}
}
private void btnMultiply_Click(object sender, EventArgs e)
{
if (txtDisplay.Text == "")
{
return;
}
else
{
multiply = true;
txtDisplay.Tag = txtDisplay.Text;
txtDisplay.Text = "";
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtDisplay.Text == "")
{
return;
}
else
{
add = true;
txtDisplay.Tag = txtDisplay.Text;
txtDisplay.Text = "";
}
}
private void btnSubtract_Click(object sender, EventArgs e)
{
if (txtDisplay.Text == "")
{
return;
}
else
{
subtract = true;
txtDisplay.Tag = txtDisplay.Text;
txtDisplay.Text = "";
}
}
private void btnEquals_Click(object sender, EventArgs e)
{
if (multiply)
{
decimal dec = Convert.ToDecimal(txtDisplay.Tag) * Convert.ToDecimal(txtDisplay.Text);
txtDisplay.Text = dec.ToString();
}
if (divide)
{
decimal dec = Convert.ToDecimal(txtDisplay.Tag) / Convert.ToDecimal(txtDisplay.Text);
txtDisplay.Text = dec.ToString();
}
if (add)
{
decimal dec = Convert.ToDecimal(txtDisplay.Tag) + Convert.ToDecimal(txtDisplay.Text);
txtDisplay.Text = dec.ToString();
}
if (subtract)
{
decimal dec = Convert.ToDecimal(txtDisplay.Tag) - Convert.ToDecimal(txtDisplay.Text);
txtDisplay.Text = dec.ToString();
}
else
{
return;
}
}
private void btnDivide_Click(object sender, EventArgs e)
{
if (txtDisplay.Text == "")
{
return;
}
else
{
divide = true;
txtDisplay.Tag = txtDisplay.Text;
txtDisplay.Text = "";
}
}
}
It looks like the problem is that you aren't clearing your operation commands. i.e. you set it to Add, but you never clear the Add when you set it to Multiply. If you look in the btnEquals_Click method, it's possible to have several operations active at once, and it will execute all of them.
Look at your btnEquals_Click event. Someone chooses to add, so add = true and it's the only if block that executes - everything good so far.
Then someone chooses to multiply, so now multiply = true, but add = true as well, so now you're multiplying and adding. If someone goes through all the operators, then (because you're never clearing your operator flags), every number thereafter will be multiplied, then divided, then added, and finally subtracted.
To fix it, you could create a method that clears the operators:
private void ResetOperatorFlags()
{
multiply = false;
divide = false;
add = false;
subtract = false;
}
Then call it before you perform an operation on the number:
private void btnMultiply_Click(object sender, EventArgs e)
{
if (txtDisplay.Text == "")
return;
ResetOperatorFlags();
multiply = true;
txtDisplay.Tag = txtDisplay.Text;
txtDisplay.Text = "";
}
Finally, in your btnEquals_Click event, use else if... you won't really need it after clearing the flags, but there's no sense in testing every flag if only one can be set at a time:
private void btnEquals_Click(object sender, EventArgs e)
{
if (multiply)
{
...
}
else if (divide)
{
...

Categories