前言
环境:Win11, Visual Studio2022
前置知识:
各控件的基本使用
C#代码基础(会加减乘除调用类即可)
效果预览
代码
说明:仅该窗体需编写代码,非编写部分不含,需自行学习
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 LearnApp1_resume
{
public partial class Calculater : Form
{
int num1 = 0, num2 = 0, state = 0, res;
string sym = null;
public Calculater()
{
InitializeComponent();
}
void StateChange()
{
string text = null;
if (num1 != 0) text += num1.ToString();
text += sym;
if (num2 != 0) text += num2.ToString();
richTextBox2.Text = text;
richTextBox1.Text = null;
}
private void button_num_Click(object sender, EventArgs e)
{
//if (richTextBox1.Text == " ") richTextBox1.Text = "111";
//if (richTextBox1.Text != " ")
//{
// num1 = 0; num2 = 0;
// state = 0;sym = null;
// richTextBox1.Text = " ";
//}
Button button = (Button)sender;
int num = Convert.ToInt16(button.Text);
if (state == 0)
num1 = num1 * 10 + num;
else
num2 = num2 * 10 + num;
StateChange();
}
private void ans()
{
switch (sym)
{
case "+":
res = num1 + num2;
break;
case "-":
res = num1 - num2;
break;
case "*":
res = num1 * num2;
break;
case "/":
res = num1 / num2;
break;
}
richTextBox1.Text = res.ToString();
//默认继承
num1 = res;
num2 = 0;
state = 1;
sym = null;
}
private void button4_Click(object sender, EventArgs e)
{
if(num2!=0) ans();
sym = "+";
state = 1;
StateChange();
}
private void button14_Click(object sender, EventArgs e)
{
if (num2 != 0) ans();
sym = "-";
state = 1;
StateChange();
}
private void button16_Click(object sender, EventArgs e)
{
if (num2 != 0) ans();
sym = "*";
state = 1;
StateChange();
}
private void button15_Click(object sender, EventArgs e)
{
if (num2 != 0) ans();
sym = "/";
state = 1;
StateChange();
}
private void button5_Click(object sender, EventArgs e)
{
StateChange();
ans();
}
private void button6_Click(object sender, EventArgs e)
{
num1 = 0; num2 = 0;
state = 0;sym = null;
richTextBox1.Text = " ";
StateChange();
}
private void Calculater_Load(object sender, EventArgs e)
{
StateChange();
richTextBox1.Text = " ";
//if (richTextBox1.Text == " ") richTextBox1.Text = "111";
}
}
}