编写计算器程序
一 准备
我的电脑有了vistual studio2010就没有用2019了。
新建一个项目,选Windows窗体应用程序,其他默认,点确定。
找到工具箱会找到一些可视化的工具。
主要使用以下工具
1.textbox:文本框控件
2.button:按钮控件
二 设计
双击或拖动控件,变成下面的样子(每个按钮记着改名字,也可以换换颜色),操作界面就整好了。
三 编写程序
双击每个不同的按钮,可以编写不同功能
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Double leftnum, rightnum, result,a;
String Flag;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
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 button11_Click(object sender, EventArgs e)
{
leftnum = Convert.ToDouble(textBox1.Text);
Flag = "-";
textBox1.Text = "";
}
private void button12_Click(object sender, EventArgs e)
{
leftnum = Convert.ToDouble(textBox1.Text);
Flag = "*";
textBox1.Text = "";
}
private void button15_Click(object sender, EventArgs e)
{
a=Convert.ToDouble(textBox1.Text) * 10;
textBox1.Text = Convert.ToString(a);
}
private void button10_Click(object sender, EventArgs e)
{
leftnum = Convert.ToDouble(textBox1.Text);
Flag = "+";
textBox1.Text = "";
}
private void button13_Click(object sender, EventArgs e)
{
rightnum = Convert.ToDouble(textBox1.Text);
if (Flag == "+")
result = leftnum + rightnum;
else if(Flag == "-")
result = leftnum - rightnum;
else if(Flag == "*")
result = leftnum * rightnum;
else if(Flag == "/")
result = leftnum / rightnum;
textBox1.Text = result.ToString();
}
private void button14_Click(object sender, EventArgs e)
{
leftnum = Convert.ToDouble(textBox1.Text);
Flag = "/";
textBox1.Text = "";
}
private void button16_Click(object sender, EventArgs e)
{
leftnum = 0;
rightnum = 0;
textBox1.Text = "";
} //归零
private void button17_Click(object sender, EventArgs e)
{
textBox1.Text += ".";
}
}
}
四 问题解决
1.texBox1.Text 的数字是字符要注意转换。
2.归零有点问题,是忘记把leftnum中存的数删除了
五 仍存在的问题
1.连按两次等于号会报错
2.不能打出零点几,可以只按.输数字,看起来可能不太好看