在一些問題中有時會用到計算器,今天我們可以用C#做一個簡易的計算器
用到的開發工具爲Visual Studio 2019(我用的是2019,其他版本的也可以)
1.首先新建一個項目文件.
2.在Form1.cs文件(Winform框架基礎文件)中添加所用到的控件.
3.添加TextBox和ComboBox以及Button控件
4.對Button以及ComboBox進行一些簡單的設置
5.設置好的界面如下圖所示:
6.界面設置好雙擊對Button1進行填寫代碼:
private void button1_Click(object sender, EventArgs e)
{
object type = comboBox1.SelectedItem;//聲明選擇欄
int num1 = int.Parse(textBox1.Text);//進行變量的聲明
double num2 = double.Parse(textBox2.Text);
if (type.ToString() == "+")//判斷comnoBox1中的值爲+
{
textBox3.Text = (num1 + num2).ToString();
}
if (type.ToString() == "-")//判斷comnoBox1中的值爲-
{
textBox3.Text = (num1 - num2).ToString();
}
if (type.ToString() == "×")//判斷comnoBox1中的值爲×
{
textBox3.Text = (num1 * num2).ToString();
}
if (type.ToString() == "÷")//判斷comnoBox1中的值爲÷
{
if (textBox1.Text=="0"|textBox2.Text=="0")//除數不能爲零
{
MessageBox.Show("輸入錯誤","提示");//否則提示輸入錯誤
}
textBox3.Text = (num1 /num2).ToString();
}
if (type.ToString() == "%")//判斷comnoBox1中的值爲%(求餘數)
{
if (textBox1.Text == "0" | textBox2.Text == "0")
{
MessageBox.Show("輸入錯誤", "提示");
}
textBox3.Text = (num1 % num2).ToString();
}
if (type.ToString()=="X^2")//判斷comnoBox1中的值爲X^2(求次方)
{
if (textBox1.Text == "0")
{
MessageBox.Show("輸入錯誤", "提示");
}
textBox3.Text = (Math.Pow(num1,num2)).ToString() ;
}
if (type.ToString()=="X^1/2")//判斷comnoBox1中的值爲X^1/2(求根)
{
textBox2.Text=" 0.5";
if (textBox1.Text == "0")//被求數不能爲零
{
MessageBox.Show("輸入錯誤", "提示");
}
textBox3.Text = (Math.Sqrt(num1)).ToString();
}
}
7.對Button2中進行代碼編寫:
private void button2_Click(object sender, EventArgs e)//點擊歸零按鈕,textBox中值爲零同時comboBox中爲空字符串
{
textBox1.Text = "0";
textBox2.Text = "0";
textBox3.Text = "0";
comboBox1.Text=" ";
}
8.對程序進行調試:
9.簡易版計算器也就完成了,有什麼不足可以留言提出來