根据已完成的程序写出自己计算器的需求,用C#制作的简单计算器

2024-11-30 04:59:42
推荐回答(1个)
回答1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace calc
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void btn_calc_Click(object sender, EventArgs e)
        {
            double n1;
            bool b1 = double.TryParse(txt_calc1.Text, out n1);
            double n2;
            bool b2 = double.TryParse(txt_calc2.Text, out n2);
            if (!b1||!b2)//判断输入的2个字符串是否能成功转换成数字类型
            {
                MessageBox.Show("输入计算数有误,请重新输入!");
                return;
            }
            switch (comboBox1.SelectedItem.ToString())//判断运算符
            {
                case "": MessageBox.Show("请选择运算符");
                    break;
                case "+": if (b1 && b2)//选择加法运算
                    {
                        txt_result.Text = (n1 + n2).ToString();
                    }
                    break;
                case "-": if (b1 && b2)
                    {
                        txt_result.Text = (n1 - n2).ToString();
                    }
                    break;
                case "*": if (b1 && b2)
                    {
                        txt_result.Text = (n1 * n2).ToString();
                    }
                    break;
                case "/": if (b1 && b2)
                    {
                        if (n2!=0)//当出书不为0时
                        {
                            txt_result.Text = (n1 / n2).ToString();
                        }
                        else
                        {
                            MessageBox.Show("除数不能为0!");
                        }
                    }
                    break;
            }
        }
        private void btn_clear_Click(object sender, EventArgs e)
        {
            txt_calc1.Text = "";
            txt_calc2.Text = "";
            txt_result.Text = "";
        }
    }
}