can perform some operations but not all on c# calculator? - c#

So far, my addition and subtraction work. But, my multiplication and division do not. This is because the first two numbers I put in get added and them the operation is done. Such as, if 9 * 9 + 3 should be 84, it is 21 on my calculator. That is because it is taking 9+9 + 3; as it only sees the last operator.
I have absolutely no idea how to fix this. Is there any helpful insight?
public partial class Form1 : Form
{
double num2;
double num1;
string c;
public Form1()
{
InitializeComponent();
}
private void btn0_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn0.Text;
}
private void btn1_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn1.Text;
}
private void btn2_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn2.Text;
}
private void btn3_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn3.Text;
}
private void btn4_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn4.Text;
}
private void btn5_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn5.Text;
}
private void btn6_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn6.Text;
}
private void btn7_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn7.Text;
}
private void btn8_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn8.Text;
}
private void btn9_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn9.Text;
}
private void btnDecimal_Click(object sender, EventArgs e)
{
if (!txtBox.Text.Contains('.'))
txtBox.Text += '.';
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBox.Clear();
}
private void btnAddition_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "+";
txtBox.Clear();
}
private void btnSubtraction_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "-";
txtBox.Clear();
}
private void btnMultiplication_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "*";
txtBox.Clear();
}
private void btnDivision_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "/";
txtBox.Clear();
}
private void btnEquals_Click(object sender, EventArgs e)
{
double result;
num2 = double.Parse(txtBox.Text);
switch (c)
{
case "+":
result = num1 + num2;
txtBox.Text = result.ToString();
num1 = 0;
break;
case "-":
result = num1 - num2;
txtBox.Text = result.ToString();
num1 = 0;
break;
case "*":
result = num1 * num2;
txtBox.Text = result.ToString();
num1 = 0;
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;
default:
result = 0;
break;
}
}
}
}

You need to do the previous operation before overwriting it with a new one:
private void btnAddition_Click(object sender, EventArgs e)
{
num2 = double.Parse(txtBox.Text);
num1 = calc(num1, num2, c);
c = "+";
txtBox.Clear();
}
where calc does the operation that you do on "=" now.

Two issues:
Look at your num1 variable every time after you click an operator other than equal. Say I start with 6*4-3. I press 6, then *. At this point num1 now becomes 6. Press 4 and - next. Now 4 is Added to Num1 making 10. Then 3 and equal is pressed, which probably gave you 7.
Second issue:
c is being overridden every time you press a different operator such as + or minus.
Solutions:
1) You could make an infix parser or
2) Modify your code to something as follow (giving example for subtraction)
private void btnSubtraction_Click(object sender, EventArgs e)
{
Equals()
c = "-";
txtBox.Clear();
}
private void btnEquals_Click(object sender, EventArgs e)
{
Equals();
txtBox.Text = Result.ToString();
result = 0;
}
private void Equals()
{
if (!double.TryParse(txtBox.Text, out num2)) return;
switch (c)
{
case "+":
result = result + num2;
break;
case "-":
result = result - num2;
break;
case "*":
result = result * num2;
break;
case "/":
result = result / num2;
break;
default:
result = num2;
break;
}
}

I think your problem is num1. Everytime you do an opperation you are just adding num1 with the value of the text box.
So I think when you press the buttons: 6*4-3= you should get 21, but you are acrually getting 7
This is because num1 is being added when you press * and - buttons, so you end up doing 6+4-3 = 7.
You need to change btnMultiplication_Click to something like:
private void btnMultiplication_Click(object sender, EventArgs e)
{
num1 = num1 * double.Parse(txtBox.Text);
c = "*";
txtBox.Clear();
}
and something similar for divide and subtract. I think subtract only works in your example because it's the last thing you do and the equals button handles it correctly.
I haven't tested this out but I think that's your problem

The mistake is that you're doing, for every operator:
num1 = num1 + double.Parse(txtBox.Text);
and that's wrong, because you're only adding every number you write in your calculator, except the last one, which is calculated correctly, due to btnEquals_Click.
In fact you check what operator you're using only when "=" is pressed, you have to do that for every operator you choose.

When any operation (+, -, /, *, =) is performed, the existing state (including the last operation) should be evaluated and replaces your first number, operation and second number.
Look at your criteria, here's the state before/after each action:
2+2+2= 6
2+
before: firstNumber=0 (default), operation="+" (default, hidden), secondNumber=2
after: firstNumber=2 (calc 0+2), operation="+", secondNumber=empty (awaiting input)
2+2+
before: firstNumber=2, operation="+", secondNumber=2
after: firstNumber=4(calc 2+2), operation="+", secondNumber=empty (awaiting input)
2+2+2=
before: 4 + 2
after: 6 + (empty)
2+3-1= 4
2+
before: 0(default) +(default) 2
after: 2 + (empty)
2+3-
before: 2 + 3
after: 5 - (empty)
2+3-1=
before: 5 - 1
after: 4 +(inferred) (empty)
6*4-3= 21
6*
before: 0(default) +(default) 6
after: 6 * (empty)
6*4-
before: 6 * 4
after: 24 - (empty)
6*4-3=
before: 24 - 3
after: 21 +(inferred) (empty)
Does that make more sense?
Also to follow standard calculator conventions you might want to consider allowing people to change the operation if the 2nd number is currently empty, e.g.
given this sequence:
6*4=-3= - perform 6*4 and see result ("="), then subtract 3 from that and show that result ("=")
6*
before: 0(default) +(default) 6 -> 6 * (empty)
6*4=: 6 * 4
after: 24 +(inferred) (empty)
6*4=-
before: 24 + (empty)
after special case: 24 - (empty)
6*4=-3=
before: 24 - 3
after: 21 +(inferred) (empty)
UPDATE:
To put this in terms of your code, you would need to change the +, -, /, * and = buttons to all work the same way. That is, take num1, c and the current value of double.Parse(txtBox.Text), perform that operation then update based on the new operation.
// is the current txtBox value new, so will be cleared and allow op change
private bool isNew = true;
// change this to default to +
string c = "+";
double num1 = 0;
private void Evaluate(string newOperand)
{
if (isNew)
{
// just update the operand, don't perform an evaluate
c = newOperand;
return;
}
double num2 = double.Parse(txtBox.Text);
switch (c)
{
case "+":
num1 = num1 + num2;
break;
// etc for -, /, *
// for "="
default:
num1 = num1 + num2;
break;
}
isNew = true;
c = newOperand;
}
// this can be assigned as the handler for buttons 0 - 9
public void btnNumber_Click(object sender, EventArgs e)
{
var button = sender as Button;
txtBox.Text += button.Text;
isNew = false;
}
// this can be assigned as the event handler for all operations: +, -, /, *, =
public void btnOperation_Click(object sender, EventArgs e)
{
var button = sender as Button;
Evaluate(button.Text);
}
I have changed the whole purpose of num1 from the way you did it, so it is now the firstNumber as in my examples above.
You might want to add a clear all that will reset num1 to 0 and c to +. You could also do this in your existing btnClear_Click by detecting a 2nd press, like many calculators do:
public void btnClear_Click(object sender, EventArgs e)
{
if (isNew)
{
num1 = 0;
c = "";
// text box should already be empty
}
else
{
isNew = true;
txtBox.Clear();
}
}

Related

How to count the 2nd number at the equal button [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I want to add a new function to my calculator. If I do 1 + 1 and press the equal button, the outcome will be 2. The function I want to add is that if I press the equal button again, there will be 1 added to 2, so the outcome is 3. When I click again on the equal button this must happen again and the outcome must be 4. This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test
{
public partial class Form1 : Form
{
string first = "";
string second = "";
string userInput = "";
string space = " ";
char function;
double result = 0.0;
public Form1()
{
InitializeComponent();
}
private void number1_Click(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput += "1";
calculatorDisplay.Text += userInput;
}
private void number2_Click(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput += "2";
calculatorDisplay.Text += userInput;
}
private void number3_Click(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput += "3";
calculatorDisplay.Text += userInput;
}
private void number4_Click(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput += "4";
calculatorDisplay.Text += userInput;
}
private void number5_Click(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput += "5";
calculatorDisplay.Text += userInput;
}
private void number6_Click(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput += "6";
calculatorDisplay.Text += userInput;
}
private void number7_Click(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput += "7";
calculatorDisplay.Text += userInput;
}
private void number8_Click(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput += "8";
calculatorDisplay.Text += userInput;
}
private void number9_Click(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput += "9";
calculatorDisplay.Text += userInput;
}
private void clearButton_Click(object sender, EventArgs e)
{
first = "";
second = "";
userInput = "";
result = 0.0;
calculatorDisplay.Text = "0";
feedback.Text = "";
}
private void divideButton_Click(object sender, EventArgs e)
{
function = '/';
first = userInput;
userInput = "";
feedback.Text = first + space + "÷";
}
private void multiplyButton_Click(object sender, EventArgs e)
{
function = '*';
first = userInput;
userInput = "";
feedback.Text = first + space + "*";
}
private void plusButton_Click(object sender, EventArgs e)
{
function = '+';
first = userInput;
userInput = "";
feedback.Text = first + space + "+";
}
private void minusButton_Click(object sender, EventArgs e)
{
function = '-';
first = userInput;
userInput = "";
feedback.Text = first + space + "-";
}
private void equalButton_Click(object sender, EventArgs e)
{
second = userInput;
double firstNum, secondNum;
firstNum = Convert.ToDouble(first);
secondNum = Convert.ToDouble(second);
if(function =='+')
{
result = firstNum + secondNum;
calculatorDisplay.Text = result.ToString();
feedback.Text = first + space + "+" + space + second + space + "=";
}
else if(function == '-')
{
result = firstNum - secondNum;
calculatorDisplay.Text = result.ToString();
feedback.Text = first + space + "-" + space + second + space + "=";
}
else if (function == '/')
{
if(secondNum == 0)
{
calculatorDisplay.Text = "Error";
}
else
{
result = firstNum / secondNum;
calculatorDisplay.Text = result.ToString();
feedback.Text = first + space + "÷" + space + second + space + "=";
}
}
else if (function == '*')
{
result = firstNum * secondNum;
calculatorDisplay.Text = result.ToString();
feedback.Text = first + space + "*" + space + second + space + "=";
}
}
private void decimalButton_Click(object sender, EventArgs e)
{
calculatorDisplay.Text += ".";
}
private void zeroButton_Click(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput += "0";
calculatorDisplay.Text += userInput;
}
}
}
I would scale down the click methods like so:
private void equalsClick(object sender, EventArgs e)
{
calculatorDisplay.Text = "";
userInput ++;
calculatorDisplay.Text += userInput;
}
And then for this I would go with
if(function =='+')
{
result = (secondNum * userInput) + firstNum ;
calculatorDisplay.Text = result.ToString();
double newSecond = (second * userInput);
feedback.Text = first + space + "+" + space + newSecond + space + "=";
}
If that makes sense. You want to count the times the user clicked. Just be sure to reset userClick to 0 on clearButton
You need to have two variables declared in the class like this
public partial class Form1 : Form
{
double result =0.00;
double lastnumber = 0.00;
}
So you will in the button click event assign values to these two variables like below:
private void number1_Click(object sender, EventArgs e)
{
lastnumber = userInput;
result = result + lastnumber;
calculatorDisplay.Text =result;
}
And If you don't know much about recursive functions or usages avoid the use of it to perform these functions.

C# Calculator using List Array error at some operations Windows Form Application

Hello I'm still new to programming and yes this is not the best code you will see... I tried making calculator on C# windows form for fun and I'm having trouble on the subtraction and division operations, but the addition and multiplication works perfectly fine for me. I decided to have a list array so that I would be able to input numbers as much as I want.
The error for the subtraction is when I input for example 5 - 2 the result will be -3
As for the division the error is that the result is always 1
Please tell me where did I go wrong and give a detailed explanation if possible so that I would understand more about programming. Thanks in advance!
namespace CalculatorTestForm1
{
public partial class Form1 : Form
{
public static List<int> Numlist = new List<int>();
public static string operation;
public Form1()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
Button Num = (Button)sender;
TXTBox.Text += Num.Text;
}
private void BPlus_Click(object sender, EventArgs e)
{
operation = "add";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BEquals_Click(object sender, EventArgs e)
{
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
int sum = 0;
int product = 1;
int quotient = 1;
int difference = 0;
if (operation == "add"){
foreach (int value in Numlist)
{
sum += value;
}
string Answer = sum.ToString();
TXTBox.Text = Answer;
}else if(operation == "minus"){
foreach (int value in Numlist)
{
difference = value - difference;
}
string Answer = difference.ToString();
TXTBox.Text = Answer;
}
else if (operation == "multiply")
{
foreach (int value in Numlist)
{
product *= value;
}
string Answer = product.ToString();
TXTBox.Text = Answer;
}
else if (operation == "divide")
{
foreach (int value in Numlist)
{
quotient = value / value;
}
string Answer = quotient.ToString();
TXTBox.Text = Answer;
}
Numlist.Clear();
}
private void BClear_Click(object sender, EventArgs e)
{
TXTBox.Text = "";
Numlist.Clear();
}
private void BMinus_Click(object sender, EventArgs e)
{
operation = "minus";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BDivide_Click(object sender, EventArgs e)
{
operation = "divide";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BMulti_Click(object sender, EventArgs e)
{
operation = "multiply";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
}
}
For the division it's obvious:
quotient = value / value;
value/value will always be 1.
There must be quotient in that loop somewhere...
For the subtraction the problem is that because of the way you do it, the order of the numbers are reversed.
lets say 5 - 2:
foreach (int value in Numlist)
{
difference = value - difference;
}
NumList = {5,2}
1st iteration:
difference = value(5) - difference(0) = 5
2nd iteration:
difference = value(2) - difference(5) = -3
You should reverse the order of the loop: NumList.Reverse()
And for the division as well:
Division:
foreach (int value in Numlist.Reverse())
{
quotient = value / quotient;
}
Subtraction:
foreach (int value in Numlist)
{
difference = value - difference;
}

desired output not coming

double num1, num2, result;
String sign = "";
protected void add_Click(object sender, EventArgs e)
{
sign = "+";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
protected void equal_Click(object sender, EventArgs e)
{
try
{
num2 = double.Parse(Convert.ToString(tb1.Text));
if(sign.Equals("+")){
result = num1 + num2;
tb1.Text = Convert.ToString(result);
}
if(sign.Equals("-")){
result = num1 - num2;
tb1.Text = Convert.ToString(result);
}
if(sign.Equals("*")){
result = num1 * num2;
tb1.Text = Convert.ToString(result);
}
if(sign.Equals("/")){
result = num1 / num2;
tb1.Text = Convert.ToString(result);
}
}
catch (Exception ex)
{
tb1.Text = ex.Message;
}
}
protected void minus_Click(object sender, EventArgs e)
{
sign = "-";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
protected void divide_Click(object sender, EventArgs e)
{
sign = "/";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
protected void product_Click(object sender, EventArgs e)
{
sign = "*";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
this is my simple program which performs arithmetic operations, but when i click '=' button it does not gives me result instead it gives me the last number entered in the textfield..
anyone knows whats the problem with code?
Web applications are stateless, a new instance of your class is created for each request (GET or POST).
Therefore the fields in the class are reinitialized on every POST:
double num1, num2, result;
String sign = "";
You need to persist the values of these fields somewhere: ViewState would be one option.
A typical ViewState-backed property implementation would look something like:
public double Num1
{
get
{
o = ViewState["Num1"];
return (o == null) 0D : (double) o;
}
set
{
ViewState["Num1"] = value;
}
}
If you replace each of your fields num1, num2, result, sign with properties implemented like this (each with a unique name of course), and ViewState is enabled, then you should get the result you want.
The sign variable is being reset to an empty string on post back by this line:
String sign = "";
You need to store the value of sign in cache so that it survives between post backs.
I recommend Session to do that, like this:
protected void minus_Click(object sender, EventArgs e)
{
sign = "-";
// Store sign in Session
Session["theSign"] = sign;
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
Note: Do this same Session storing logic in the other event handlers for divide and product.
Now in Page_Load you need to check the Session for the sign value every time, like this:
protected void Page_Load(object sender, EventArgs e)
{
// Default sign value that may be changed by value in session cache
String sign = "";
// Is there a session value for theSign
if(Session["theSign"] != null)
{
// Yes, so set the sign variable value to use in click event handlers
sign = Session["theSign"].ToString();
}
}

Problems in windows application with error handling and textbox display

I wrote out a very simple code. I am trying to get it to do two things for me
I want it to continually show the user inputs and what the output would be. Right now it does not. I think this is a problem with my appendtext
should I use a try and catch for error handling? That's if the user enters more than one decimal my code crashes. I would like to know how to make it where it reverts back to one decimal and continues on.
Here is a snippet of my code.
Also to note, only in my addition method did I start the appendtext, since it didn't work and I kept getting stuck I stopped and came here...
private void button10_Click(object sender, EventArgs e) {
textBox1.AppendText(".");
}
private void button3_Click(object sender, EventArgs e) {
c = "+";
num1 = double.Parse(textBox1.Text);
textBox1.AppendText("+");
}
private void button12_Click(object sender, EventArgs e) {
c = "-";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button13_Click(object sender, EventArgs e) {
c = "*";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button14_Click(object sender, EventArgs e) {
c = "/";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button4_Click(object sender, EventArgs e) {
num2 = double.Parse(textBox1.Text);
double result;
if (c == "+") {
result = num1 + num2;
textBox1.Text = result.ToString();
}
When you append "+", the num2 is equal to value1+"+"+value2 or something so try to use this code
private void button4_Click(object sender, EventArgs e) {
double result;
if (c == "+") {
num2 = double.Parse(textBox1.Text.Split('+')[1]);//bad idea but will work
result = num1 + num2;
textBox1.Text = result.ToString();
}
}
also try
private void button4_Click(object sender, EventArgs e) {
double result;
if (c == "+") {
num2 = double.Parse(textBox1.Text.SubString(textBox1.Text.LastIndexOf('+')+1));
result = num1 + num2;
textBox1.Text = result.ToString();
}
}
PS: try catch needed!

use parentheses in c# calculator

Hello I just write a simple calculator in C# and I want to improve my program to handle parentheses.
Here is my button to add 1(digit):
private void btnOne_Click(object sender, EventArgs e)
{
txtResult.Text += '1';
}
This is a method for my Plus button:
private void btnPlus_Click(object sender, EventArgs e)
{
lblChar.Text = "+";
num1 = float.Parse(txtResult.Text);
txtResult.Text = "";
}
And this is for to calculate final result:
private void btnEqual_Click(object sender, EventArgs e)
{
num2 = float.Parse(txtResult.Text);
if (lblChar.Text == "+")
{
num3 = num1 + num2;
txtResult.Text = Convert.ToString(num3);
}
}
Anyone can help me to write parentheses for my program?
You can use NCalc - Mathematical Expressions Evaluator for .NET
Expression e = new Expression("2 + (3 + 5)*6");
var result = e.Evaluate();

Categories

Resources