首先,刚入门C#可视化,跟老师学习了制作计算器(粗糙版)
用到了Button,Label和TextBox
经测试,正常(包括小数部分)
其中除数为零的处理方式为弹窗显示无穷大,并强制清零
因为测试时发现TextBox显示无穷大后再按符号会出错
以下是代码
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 Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double i, j, k;
char a;
private void button1_Click(object sender, EventArgs e)
{
//MessageBox.Show("1");
textBox1.Text += "1";
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text += "2";
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text += "3";
}
private void button4_Click(object sender, EventArgs e)
{
textBox1.Text += "4";
}
private void button5_Click(object sender, EventArgs e)
{
textBox1.Text += "5";
}
private void button6_Click(object sender, EventArgs e)
{
textBox1.Text += "6";
}
private void button7_Click(object sender, EventArgs e)
{
textBox1.Text += "7";
}
private void button8_Click(object sender, EventArgs e)
{
textBox1.Text += "8";
}
private void button9_Click(object sender, EventArgs e)
{
textBox1.Text += "9";
}
private void button0_Click(object sender, EventArgs e)
{
textBox1.Text += "0";
}
private void point_Click(object sender, EventArgs e)
{
textBox1.Text += ".";
}
private void equal_Click(object sender, EventArgs e)
{
j = Convert.ToDouble(textBox1.Text);
switch(a)
{
case '+':
k = i + j;
textBox1.Text = k.ToString();
break;
case '-':
k = i - j;
textBox1.Text = k.ToString();
break;
case '*':
k = i * j;
textBox1.Text = k.ToString();
break;
case '/':
if(i==0)
{
MessageBox.Show("∞");
textBox1.Text = "";
break;
}
k = i / j;
textBox1.Text = k.ToString();
break;
}
}
private void add_Click(object sender, EventArgs e)
{
i = Convert.ToDouble(textBox1.Text);
textBox1.Text = "";
a = '+';
}
private void subtraction_Click(object sender, EventArgs e)
{
i = Convert.ToDouble(textBox1.Text);
textBox1.Text = "";
a = '-';
}
private void multiplication_Click(object sender, EventArgs e)
{
i = Convert.ToDouble(textBox1.Text);
textBox1.Text = "";
a = '*';
}
private void division_Click(object sender, EventArgs e)
{
i = Convert.ToDouble(textBox1.Text);
textBox1.Text = "";
a = '/';
}
private void clear_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
private void fraction_Click(object sender, EventArgs e)
{
i = Convert.ToDouble(textBox1.Text);
if (i == 0)
{
MessageBox.Show("∞");
textBox1.Text = "";
}
else
{
i = 1 / i;
textBox1.Text = Convert.ToString(i);
}
}
}
}