自学C#已经两周了,之前写了一个简单的秒表,感觉不过瘾,觉得是不是可以试着做个功能更复杂的小程序来练练手。
于是我想到了做计算器。但是尝试之后发现做好一个计算器不简单,你需要考虑运算符的优先级,需要考虑中间结果的保存,需要考虑除零的情况,需要考虑浮点情况等等。
当然,我没有时间去做一个功能很复杂的科学计算器,也没有精力去做一个运算速度极佳的并行计算器。我的目的只是通过简单的项目提升对C#的掌握程度。
下面开始正题。。
首先设计一个简单的计算器界面。
需要17个button,一个label,一个textbox(显示结果),界面设计结果如下:
想显得高端一点,我给按钮都加了背景图片,但是貌似我图没抠好,导致效果很差,将就着看吧,哈哈。
需要说明的是,我只做了二目运算,即输入进去的操作符只支持一个运算符,然后必须点击“=”,进行运算。不支持2+3x5这种运算符的运算。
计算器的功能想必大家都懂,我不在此处写出。不废话了,直接贴代码:
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 Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button2_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button3_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button4_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button5_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button6_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button7_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button8_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button9_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button10_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button12_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text = textBox1.Text + " " + btn.Text + " ";//空格用于分隔数字各运算符
}
private void button13_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text = textBox1.Text + " " + btn.Text + " ";//空格用于分隔数字各运算符
}
private void button14_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text = textBox1.Text + " " + btn.Text + " ";//空格用于分隔数字各运算符
}
private void button15_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text = textBox1.Text + " " + btn.Text + " ";//空格用于分隔数字各运算符
}
private void button16_Click(object sender, EventArgs e)
{
textBox1.Text = "";
}
private void button17_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}
private void button11_Click(object sender, EventArgs e)
{
Single r; //用于保存计算结果
string t = textBox1.Text; //t用于保存文本框中的算术表达式
int space = t.IndexOf(