create calculator in csharp

To create a basic calculator in C#, we can use a simple GUI with buttons representing the digits, operators, and other features such as clearing, equals, and decimal point.

Here is a sample code:

main.cs
using System;
using System.Windows.Forms;

namespace Calculator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        double value = 0;
        string operation = "";
        bool operation_pressed = false;

        private void button_Click(object sender, EventArgs e)
        {
            if ((result.Text == "0") || (operation_pressed))
                result.Clear();

            operation_pressed = false;
            Button b = (Button)sender;
            result.Text += b.Text;
        }

        private void operator_Click(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            operation = b.Text;
            value = Double.Parse(result.Text);
            operation_pressed = true;
            equation.Text = value + " " + operation;
        }

        private void button16_Click(object sender, EventArgs e)
        {
            equation.Text = "";
            switch (operation)
            {
                case "+":
                    result.Text = (value + Double.Parse(result.Text)).ToString();
                    break;
                case "-":
                    result.Text = (value - Double.Parse(result.Text)).ToString();
                    break;
                case "*":
                    result.Text = (value * Double.Parse(result.Text)).ToString();
                    break;
                case "/":
                    result.Text = (value / Double.Parse(result.Text)).ToString();
                    break;
                default:
                    break;
            }
            operation = "";
        }

        private void button18_Click(object sender, EventArgs e)
        {
            result.Text = "0";
            value = 0;
        }

        private void button17_Click(object sender, EventArgs e)
        {
            result.Text = "0";
            equation.Text = "";
            value = 0;
        }

        private void button19_Click(object sender, EventArgs e)
        {
            if (!result.Text.Contains("."))
                result.Text += ".";
        }
    }
}
2149 chars
79 lines

This code creates a basic calculator with add, subtract, multiply, and divide operations, as well as clear and decimal point functions. It uses a TextBox to display the input and output, and buttons to represent the various functions.

related categories

gistlibby LogSnag