VB计算器代码
VB计算器(界面设计全部代码)
VB计算器此计算器能够实现加减乘除等一系列的功能。
还有实现显示系统时间的附加功能。
程序设计:0-9和点在command1的组内。
其他的按钮式运算符和其他功能。
正切和余切有对特殊值进行警告,除也有对除数为零的情况提示警告,还有阶乘等一系列计算溢出的情况提出警告,还有很多需要完善。
这仅供参考。
Public sum As DoublePublic k As Stri ngPublic dia n As Boolea nPublic b As In tegerPublic poin tflag As Boolea nDim clearFlag As Boolea nPublic F As Long'Dim start As boole nPublic resl As Boolean ' 运算结果存储在resl里数字按钮在一个组内,点Public ff As Double 'resl 里是否为空'llllllllllllllllllllllllllllllllllllllllllllllllllllllll击按钮输入数字 lllllllllllllllllllllllllllllllllllllllllllPrivate Sub comma nd1_click(l ndex As In teger) Select Case In dex Case 1If Not clearFlag The n ' 不是等号,那么显示 1 Text1.Text = Text1.Text & 1 Else'是等号,那么清空Text1.Text = 1 clearFlag = False End IfIf Len(Text1.Text) = 2 And InStr(1, Text1, "0") = 1 Then Text1 = Right(Text1, 1) '如果第一位的数位 0,字符串的长度为 2.那么取字符串右面的数,即两个数中右面的数Case 2If Not clearFlag Then Text1.Text = Text1.Text & 2 ElseText1.Text = 2 clearFlag = False End IfIf Len (Text1.Text) = 2 And In Str(1, Text1, "0") = 1 The n Text1 : Case 3 If Not clearFlag The n Text1.Text = Text1.Text & 3 Else=Right(Text1, 1)Text1.Text clearFlag = End If=3 False If Len (Text1.Text) = 2 And In Str(1, Text1, "0") = 1 The n Text1 : =Right(Text1, 1)Case 4If Not clearFlag The nText1.Text =Text1.Text & 4ElseText1.Text =4clearFlag = FalseEnd IfIf Len (Text1.Text) = 2 And In Str(1, Text1, "0") = 1 The n Text1 : =Right(Text1, 1)Case 5If Not clearFlag ThenTextl.Text = Textl.Text & 5 ElseTextl.Text = 5 clearFlag = False End IfIf Len(Text1.Text) = 2 And InStr(1, Text1, "0")= =1 The n Text1 ==Right(Text1, 1)Case 6If Not clearFlag The nText1.Text =Text1.Text & 6ElseText1.Text =6clearFlag = End IfFalseIf Len(Text1.Text) = 2 And InStr(1, Text1, "0")= =1 The n Text1= =Right(Text1, 1)Case 7If Not clearFlag The n Text1.Text = Text1.Text & 7 ElseTextl.Text = 7 clearFlag = False End IfIf Len(Textl.Text) = 2 And InStr(1, Textl, "0") = 1 Then Textl = Right(Text1, 1) Case 8If Not clearFlag The n Textl.Text = Textl.Text & 8 ElseTextl.Text = 8 clearFlag = False End IfIf Len(Textl.Text) = 2 And InStr(1, Textl, "0") = 1 Then Textl = Right(Text1, 1) Case 9If Not clearFlag The n Text1.Text = Text1.Text & 9 ElseText1.Text = 9 clearFlag = False End IfIf Len(Text1.Text) = 2 And InStr(1, Text1, "0") = 1 Then Text1 = Right(Text1, 1) Case 0定义加号按钮 //////////////////////////////////////If Not clearFlag Then Textl.Text = Textl.Text & 0 ElseText1.Text = 0 clearFlag = False End IfIf Len(Text1.Text) = 2 And InStr(1, Text1, "0") = 1 Then Text1 = Right(Text1, 1) Case 10If Not clearFlag The n Text1.Text = Text1.Text + "." ElseText1.Text ="" clearFlag = False End If7///////////////////////////////////////////////// 对输入点 的个数进行约 束///////////////////////////////////////////////////////////If (In Str(Text1.Text, ".")= =1) The n 对点的处理,检查是否有点,有点再输入的话为空,否则加入其中Textl.Text =""End IfIf InStr(Text1.Text, ".") < Len(Textl.Text) Then Textl.Text = Left(Text1.Text, Len(Textl.Text) - 1) End IfEnd SelectText1.SetFocus End Sub '////////////////////////Private Sub comma nd2_click() If Text1.Text = "" The n End IfIf Trim(Text1.Text) <> "" Then sum = Text1.Text Text1.Text ="" k = "+" Else Exit Sub End If End Sub 7////////////////////////定义减号按钮 ////////////////////////////////////// Private Sub comma nd3_click()定义除号按钮If Text1.Text = "" Then End IfIf Trim(Text1.Text) <> "" The n sum = Text1.Text ' 第一个数字填入方框里 Text1.Text =""' 方框的值置空k ="-" Else Exit Sub End If End Sub '///////////////////////定义乘号按钮 ////////////////////////////////////////Private Sub comma nd4_click()If Text1.Text = "" The n End IfIf Trim(Text1.Text) <> "" Then sum = Text1.Text Text1.Text ="" k = "*" Else Exit Sub End If End Sub '/////////////////////////////////////////////////////////////////// Private Sub comma nd5_click() If Text1.Text = "" Then End IfIf Trim(Text1.Text) <> "" Then sum = Text1.Text Text1.Text ="" k = "/" Else Exit Sub End If End Sub'IIIIIIIIIIIIIIIIIIIIIIIIIIII 定 义sin号 按钮/////////////////////////////////////Private Sub comma nd1O_click() If Text1.Text = "" Then End IfIf Trim(Text1.Text) <> "" The n sum = Text1.TextElseExit SubEnd IfEnd Sub'///////////////////////////// 定义cos 按钮/////////////////////////////////////Private Sub comma nd11_click()If Text1.Text = "" The nEnd IfIf Trim(Text1.Text) <> "" The nsum = Text1.Textk ="cos"ElseExit SubEnd IfEnd Sub'///////////////////////////// 定义tan 按钮////////////////////////////////////Private Sub comma nd12_click()If Text1.Text = "" The nEnd IfIf Trim(Text1.Text) <> "" The nsum = Text1.Textk = "tan"ElseExit SubEnd IfEnd Sub'////////////////////////// 定义cot 按钮//////////////////////////////////////Private Sub comma nd13_click()If Text1.Text = "" The nEnd IfIf Trim(Text1.Text) <> "" Then sum = Textl.Textk = "cot"ElseExit SubEnd IfEnd Sub7////////////////////////// 定义人按钮///////////////////////////////////////Private Sub Comma nd14_click()If Textl.Text = "" The nExit SubIf Trim(Textl.Text) <> "" The nsum = Textl.TextTextl.Text =""k = "A"ElseExit SubEnd IfEnd Sub'///////////////////////// 定义2A ///////////////////////////////////////////Private Sub comma nd15_click()If Textl.Text = "" The nExit SubEnd IfIf Trim(Textl.Text) <> "" The nsum = Textl.Textk = "2人"ElseExit SubEnd IfEnd Sub'/////////////////////// 定义3A 按钮/////////////////////////////////////////// Private Sub comma nd16_click()If Textl.Text = "" The nExit SubEnd IfIf Trim(Textl.Text) <> "" The nsum = Textl.Textk = "3A"ElseExit SubEnd IfEnd Sub'IIIIIIIIIIIIIIIIIIII定义X!按钮///////////////////////////////////////////// Private Sub comma nd17_click()If Text1.Text = "" The nExit SubEnd IfIf Trim(Text1.Text) <> "" The nsum = Text1.Textk = "x!"ElseExit SubEnd If'////////////////// 定义sqrt 按钮////////////////////////////////////////////// Private Sub comma nd18_click()If Text1.Text = "" The nExit SubEnd IfIf Trim(Text1.Text) <> "" The nsum = Text1.Textk = "sqrt"ElseExit SubEnd IfEnd Sub'///////////////////////////// 定义阶乘的函数////////////////////////////////// Private Fu nction Ni(N As Long) As Boolea n 'Ni = FalseDim Mm As Long 'Dim F1 As Lo ngF = 1For Mm = 1 To NIf Mm > 12 The n 'If F1 > The n Ni = False Exit Fun cti on End IfF = F * MmNext MmNi = TrueEnd FunctionPrivate Sub equalbut_click() clearFlag = FalseEnd SubPrivate Sub comma nd6_click()If Trim(Text1.Text) <> "" Then 'Dim F As DoubleDim a As DoubleDim pi As DoubleDim i, j As In tegerpi = 3.14159265358979If Text1.Text > 2147483647 ThenMsgBox "溢出,请确认", vbExclamation, Me.CaptionExit SubEnd If a = Text1.Text clearFlag = TrueIf k = "+" Then sum = sum + a Text1.Text = sumElseIf k = "s in" The n sum = Sin(a * pi / 180) Textl.Text = sumElseIf k = "cos" ThenDim t As In tegert = a Mod 180 - 90If t = 0 ThenText1.Text = 0If m = 0 The n MsgBox " ElseElsesum = Cos(a * pi / 180) Textl.Text = sum End IfElseIf k = "tan" Then Dim m As In teger Dim N As In teger m = a Mod 180 - 90(90+180*n )度的正切值无意义,请重新输入 sum = (Tan(a * pi / 180)) Textl.Text = sum End IfElseIf k = "cot" The n If a = 0 The n MsgBox "0 度余切没有意义!请重新输入!Elsesum = 1 / (Tan(a * pi / 180)) Textl.Text = sum End If'ElseIf k = "x!" The n 'If Text1.Text > 0 The n 'Call fact(Text1.Text, F) ' Text1.Text = F'ElseIf Text1.Text = 0 The n 'sum = 1' Text1.Text = sum'ElseIf Text1.Text < 0 The n 'MsgBox " 负数没有阶乘! ”'End If减法运算Elself k = "x!" The nIf Ni(Textl.Text) = False The nMsgBox "溢出", vbExclamation, Me.CaptionText1.Text =""Exit SubElseText1.Text = FEnd IfElself k = "2A " The nTextl.Text = Val(Textl.Text) * Val(Textl.Text)Elself k = "3A" The nTextl.Text = Val(Textl.Text) * Val(Textl.Text) * Val(Textl.Text) Elself k = "sqr" The nIf a >= 0 The nsum = Math.Sqr(a)Textl.Text = sumElseMsgBox "开方数不能为负数!”End If Elself k = "A" The n sum =sum A a Textl.Text = sum Elself k = "-" The n sum = sum - a Textl.Text = sum resl = 1Elself k = "*" The n sum = sum * a Textl.Text = sum Elself k = "/" The nIf Textl.Text = 0 The nMsgBox "除数不能为零!请重新输入Textl.Text =""Elsesum = sum / aTextl.Text = sumIf Len( Textl.Text) > 14 The nMsgBox "溢出,请确认", vbExclamation, Me.Caption Exit SubEnd IfExit SubEnd IfEnd IfEnd IfEnd SubPrivate Sub Comma nd9_Click()If Len(Text1.Text) >= 2 ThenText1.Text = Left(Text1.Text, Len(Text1.Text) - 1) ElseText1.Text =""End IfEnd SubPrivate Sub form」。
VB简易计算器代码
VB简易计算器代码下面是一个简单的VB计算器代码,用于执行基本的加、减、乘、除运算。
```vbOption Strict OnPublic Class CalculatorPrivate Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.ClickDim num1 As Double = CDbl(txtNum1.Text)Dim num2 As Double = CDbl(txtNum2.Text)Dim result As Double = num1 + num2txtResult.Text = result.ToStringEnd SubPrivate Sub btnSubtract_Click(sender As Object, e As EventArgs) Handles btnSubtract.ClickDim num1 As Double = CDbl(txtNum1.Text)Dim num2 As Double = CDbl(txtNum2.Text)Dim result As Double = num1 - num2txtResult.Text = result.ToStringPrivate Sub btnMultiply_Click(sender As Object, e As EventArgs) Handles btnMultiply.ClickDim num1 As Double = CDbl(txtNum1.Text)Dim num2 As Double = CDbl(txtNum2.Text)Dim result As Double = num1 * num2txtResult.Text = result.ToStringEnd SubPrivate Sub btnDivide_Click(sender As Object, e As EventArgs) Handles btnDivide.ClickDim num1 As Double = CDbl(txtNum1.Text)Dim num2 As Double = CDbl(txtNum2.Text)If num2 = 0 ThenMessageBox.Show("除数不能为0!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)ElseDim result As Double = num1 / num2txtResult.Text = result.ToStringEnd IfEnd Sub```此代码创建了一个简单的窗体应用程序,其中包含两个文本框用于输入两个数字,四个按钮用于执行不同的计算操作,以及一个文本框用于显示结果。
VB简单计算器(截图附代码)
VB程序简单计算器最近学完VB,感觉很好,写了个计算器程序,虽然花了不少时间,可也着实高兴。
其中遇到很多问题,最终也在各种资料中得到解决。
现在附上截图和全部代码,希望和大家交流一下,相互学习。
也希望能帮助到准备做计算器的同学。
计算器最终执行文件图标:计算器包括三个窗体(form):主页面form1:其中的“欢迎各位到此一游”是闪烁效果,呵呵,是自己想着无聊,就想出这么个玩意。
与计算器计算功能无关。
具体实现看下来代码。
Form1的实现代码:Public haha As BooleanPrivate Sub Command1_Click()Dim a As Integera = MsgBox("亲爱的你,真的想要退出本系统吗?", _vbYesNo + vbInformation + vbDefaultButton1, "退出系统前的询问撒(⊙o⊙)")If a = 6 Then '表示当选择“是”的时候的返回值EndEnd IfEnd SubPrivate Sub Command2_Click()Me.HideForm2.ShowEnd SubPrivate Sub Command3_Click()Me.HideForm3.ShowEnd SubPrivate Sub Form_Load()haha = FalseEnd SubPrivate Sub Timer1_Timer()haha = Not hahaIf haha ThenLabel2.ForeColor = &HFF00FFElseLabel2.ForeColor = vbWhiteEnd IfEnd Sub有些像图像等一些可见的控件属性就没在代码里写了,直接在属性里设置了。
页面(form2):此页面将鼠标点上去,还有意想不到的效果喲。
全部代码为:Dim isFocus1, isFocus2 As BooleanPrivate Sub Command1_Click()If isFocus1 Then '判断焦点在那个文本框中,便于实现按钮输入Text1.Text = Text1.Text & 0End IfIf isFocus2 ThenText2.Text = Text2.Text & 0End IfEnd SubPrivate Sub Command10_Click() If isFocus1 ThenText1.Text = Text1.Text & 9 End IfIf isFocus2 ThenText2.Text = Text2.Text & 9 End IfEnd SubPrivate Sub Command11_Click() If isFocus1 ThenText1.Text = Text1.Text & "." End IfIf isFocus2 ThenText2.Text = Text2.Text & "." End IfEnd SubPrivate Sub Command12_Click() If isFocus1 ThenText1.Text = -Val(Text1.Text)End IfIf isFocus2 ThenText2.Text = -Val(Text2.Text)End IfEnd SubPrivate Sub Command13_Click()Dim a As Integera = Val(Text1.Text) + Val(Text2.Text)Text3.Text = Val(Text1.Text) & "+" & Val(Text2.Text) & "=" & aIf Text1.Text = "" Or Text2.Text = "" ThenMsgBox "哼哼,双目运算一定要是两个数喔" & vbCrLf & vbCrLf & _ "不用说,补上去是必须的撒", vbCritical, "温馨小提醒(*^__^*)" End IfEnd SubPrivate Sub Command14_Click()Dim a As Integera = Val(Text1.Text) - Val(Text2.Text)Text3.Text = Val(Text1.Text) & "-" & Val(Text2.Text) & "=" & aIf Text1.Text = "" Or Text2.Text = "" ThenMsgBox "哼哼,双目运算一定要是两个数喔" & vbCrLf & vbCrLf & _ "不用说,补上去是必须的撒", vbCritical, "温馨小提醒(*^__^*)" End IfEnd SubPrivate Sub Command15_Click()a = Val(Text1.Text) * Val(Text2.Text)Text3.Text = Val(Text1.Text) & "×" & Val(Text2.Text) & "=" & aIf Text1.Text = "" Or Text2.Text = "" ThenMsgBox "哼哼,双目运算一定要是两个数喔" & vbCrLf & vbCrLf & _ "不用说,补上去是必须的撒", vbCritical, "温馨小提醒(*^__^*)" End IfEnd SubPrivate Sub Command16_Click() '除法的特殊性,除数不能为零If Val(Text2.Text) Thena = Val(Text1.Text) / Val(Text2.Text)Text3.Text = Val(Text1.Text) & "÷" & Val(Text2.Text) & "=" & aIf Text1.Text = "" Or Text2.Text = "" ThenMsgBox "哼哼,双目运算一定要是两个数喔" & vbCrLf & vbCrLf & _ "不用说,补上去是必须的撒", vbCritical, "温馨小提醒(*^__^*)" End IfElseText3.Text = "无穷大∞"MsgBox "亲,除数不可以为零的哟!", vbInformation, "矮油,不得了嘞(*^__^*)"Text2.Text = ""Text2.SetFocusEnd IfEnd SubPrivate Sub Command17_Click() '实现清零,并将焦点给文本框1Text1.Text = ""Text2.Text = ""Text3.Text = ""Text1.SetFocusEnd SubPrivate Sub Command18_Click()Me.Hide '进入计算器1Form1.ShowEnd SubPrivate Sub Command2_Click() If isFocus1 ThenText1.Text = Text1.Text & 1 End IfIf isFocus2 ThenText2.Text = Text2.Text & 1 End IfEnd SubPrivate Sub Command3_Click() If isFocus1 ThenText1.Text = Text1.Text & 2 End IfIf isFocus2 ThenText2.Text = Text2.Text & 2 End IfEnd SubPrivate Sub Command4_Click() If isFocus1 ThenText1.Text = Text1.Text & 3 End IfIf isFocus2 ThenText2.Text = Text2.Text & 3 End IfEnd SubPrivate Sub Command5_Click() If isFocus1 ThenText1.Text = Text1.Text & 4 End IfIf isFocus2 ThenText2.Text = Text2.Text & 4 End IfEnd SubPrivate Sub Command6_Click() If isFocus1 ThenText1.Text = Text1.Text & 5 End IfIf isFocus2 ThenText2.Text = Text2.Text & 5 End IfEnd SubPrivate Sub Command7_Click() If isFocus1 ThenText1.Text = Text1.Text & 6 End IfIf isFocus2 ThenText2.Text = Text2.Text & 6 End IfEnd SubPrivate Sub Command8_Click() If isFocus1 ThenText1.Text = Text1.Text & 7 End IfIf isFocus2 ThenText2.Text = Text2.Text & 7 End IfEnd SubPrivate Sub Command9_Click() If isFocus1 ThenText1.Text = Text1.Text & 8End IfIf isFocus2 ThenText2.Text = Text2.Text & 8End IfEnd SubPrivate Sub Form_Load()isFocus1 = False: isFocus2 = FalseEnd SubPrivate Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)Label4.ForeColor = vbBlackLabel4.FontUnderline = FalseLabel4.FontBold = FalseEnd SubPrivate Sub Label4_Click()Form3.ShowEnd SubPrivate Sub Label4_MouseMove(Button As Integer, Shift As Integer, X AsSingle, Y As Single)Label4.ForeColor = vbGreen Label4.FontUnderline = True Label4.FontBold = True End SubPrivate Sub Text1_GotFocus() isFocus1 = TrueisFocus2 = FalseEnd SubPrivate Sub Text2_GotFocus() isFocus2 = TrueisFocus1 = FalseEnd Sub页面(form3):这里面的亮点自己找哦。
vb编写的计算器代码
Option ExplicitConst CC1 = 1E+28, CC2 = 0.000000000000001, CC3 = 100000000000000# Dim Op1, Op2 ' 预先输入操作数。
Dim DecFlag% ' 小数点存在吗?Dim Klast ' 指示上一次按键事件的类型。
Dim OpFlag ' 指示未完成的操作。
Dim Kedt% ' 指示键入状态,0-未操作,1-算过,2-改过Dim MemNum ' 存储器Dim Temp2'Function sqr28(a As V ariant) As V ariantDim c As Doublec = Sqr(a)If c > CC3 Or c < CC2 Thensqr28 = cElsesqr28 = CDec(Sqr(a))sqr28 = sqr28 - (sqr28 * sqr28 - a) / sqr28 * 0.5End IfEnd FunctionFunction cur28(a As V ariant) As V ariantDim t As V ariant, c As Doublec = Abs(a) ^ (1 / 3)If c > 1000000000# Or c < 0.000000001 Thencur28 = c * Sgn(a)Elsecur28 = CDec(c) * Sgn(a)t = cur28 * cur28cur28 = cur28 - (cur28 * t - a) / t / 3End IfEnd Function' 存入存储器Private Sub BtMS_Click()If Kedt = 2 Then GetOp1MemNum = Op1LabMem.Visible = MemNum <> 0Kedt = 1End Sub' 取出存储器数据Private Sub BtMr_Click()CancelEntry_ClickOp1 = MemNumDisp = Op1Kedt = 1End Sub' 清除存储器Private Sub BtMC_Click()MemNum = CDec(0)LabMem.Visible = FalseEnd SubPrivate Sub BtOff_Click()EndEnd SubPrivate Sub Form_KeyPress(KeyAscii As Integer) Dim K As StringK = Chr(KeyAscii)'Select Case KCase Chr(24): EndCase Chr(8): CancelEntry_ClickCase Chr(27): Cancel_ClickCase "0" To "9": Number_Click KeyAscii - 48 Case ".": Decimal_ClickCase "=": Equal_ClickCase "s": BtMS_ClickCase "c": BtMC_ClickCase "r": BtMr_ClickCase "%": Func_Click 4Case "^": Func_Click 1Case "+": Operator_Click 1Case "-": Operator_Click 3Case "*": Operator_Click 2Case "/": Operator_Click 0Case "i": Func_Click 2Case "'": Func_Click 3Case "]": Func_Click 5Case "\": Func_Click 0Case ";": negcmd_ClickEnd SelectEqual.SetFocusEnd Sub' 窗体的初始化过程' 设置所有变量为其初始值。
VB简易计算器代码
VB简易计算器代码以下是一个简单的VB计算器代码:```Public Class Form1Dim firstNum As Double ' 第一个数字Dim secondNum As Double ' 第二个数字Dim operation As Integer ' 1-加法,2-减法,3-乘法,4-除法Private Sub Button0_Click(sender As Object, e As EventArgs) Handles Button0.ClickTextBoxResult.Text = TextBoxResult.Text & "0"End SubPrivate Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.ClickTextBoxResult.Text = TextBoxResult.Text & "1"End SubPrivate Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.ClickTextBoxResult.Text = TextBoxResult.Text & "2"End SubHandles Button3.ClickTextBoxResult.Text = TextBoxResult.Text & "3"End SubPrivate Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.ClickTextBoxResult.Text = TextBoxResult.Text & "4"End SubPrivate Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.ClickTextBoxResult.Text = TextBoxResult.Text & "5"End SubPrivate Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.ClickTextBoxResult.Text = TextBoxResult.Text & "6"End SubPrivate Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.ClickTextBoxResult.Text = TextBoxResult.Text & "7"End SubHandles Button8.ClickTextBoxResult.Text = TextBoxResult.Text & "8"End SubPrivate Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.ClickTextBoxResult.Text = TextBoxResult.Text & "9"End SubPrivate Sub ButtonDot_Click(sender As Object, e As EventArgs) Handles ButtonDot.ClickIf Not TextBoxResult.Text.Contains(".") ThenTextBoxResult.Text = TextBoxResult.Text & "."End IfEnd SubPrivate Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.ClickfirstNum = Double.Parse(TextBoxResult.Text)TextBoxResult.Text = ""operation = 1End SubPrivate Sub ButtonSubtract_Click(sender As Object, e As EventArgs) Handles ButtonSubtract.ClickfirstNum = Double.Parse(TextBoxResult.Text)TextBoxResult.Text = ""operation = 2End SubPrivate Sub ButtonMultiply_Click(sender As Object, e As EventArgs) Handles ButtonMultiply.ClickfirstNum = Double.Parse(TextBoxResult.Text)TextBoxResult.Text = ""operation = 3End SubPrivate Sub ButtonDivide_Click(sender As Object, e As EventArgs) Handles ButtonDivide.ClickfirstNum = Double.Parse(TextBoxResult.Text)TextBoxResult.Text = ""operation = 4End SubPrivate Sub ButtonClear_Click(sender As Object, e As EventArgs) Handles ButtonClear.ClickTextBoxResult.Text = ""End SubPrivate Sub ButtonEquals_Click(sender As Object, e As EventArgs) Handles ButtonEquals.ClickDim result As DoublesecondNum = Double.Parse(TextBoxResult.Text)Select Case operationCase 1result = firstNum + secondNumCase 2result = firstNum - secondNumCase 3result = firstNum * secondNumCase 4result = firstNum / secondNumEnd SelectTextBoxResult.Text = result.ToStringEnd SubEnd Class```这个计算器包括数字按钮0-9、小数点按钮、加法、减法、乘法、除法和等于按钮。
计算器(用vb)代码
计算器(用vb)代码Dim dflag As IntegerDim I As IntegerDim opnre As IntegerDim prev As DoubleDim oflag As IntegerDim ind As IntegerDim soundbz As BooleanDim ProgramPath As StringPrivate Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal Y As Long, ByVal Cx As Long, ByVal Cy As Long, ByVal wFlags As Long) As LongPublic Sub SetOnTop(ByVal IsOnTop As Integer)Dim rtn As LongIf IsOnTop = 1 Then'将窗口置于最上面rtn = SetWindowPos(Me.hwnd, -1, 0, 0, 0, 0, 3)Elsertn = SetWindowPos(Me.hwnd, -2, 0, 0, 0, 0, 3)End IfEnd SubPrivate Sub Check1_Click()If Check1.Value = 1 ThenSetOnTop 1ElseSetOnTop 0End IfEnd SubPrivate Sub Command1_Click(Index As Integer)text1 = Trim(text1)If Len(text1) > 20 ThenBeepExit SubEnd Ifsoundbz = Falsemand = "Close"MMControl1.FileName = ProgramPath & "/声音文件/" & Index & ".wav"mand = "Open"mand = "Play"If ind = 4 Thenprev = 0text1.Caption = " "ind = 0End Ifopnre = 0If oflag = 0 Thentext1.Caption = " "End Ifoflag = 1If Command1(Index).Caption <> "." ThenIf text1.Caption <> " 0" Thentext1.Caption = text1.Caption & Command1(Index).CaptionText = Mid(text1, 1, 1)If Text = "." Thentext1 = "0" & text1End IfElsetext1.Caption = " " & Command1(Index).CaptionEnd IfElseIf dflag = 0 Thentext1.Caption = text1.Caption & "."dflag = 1ElseCommand6.SetFocusExit SubEnd IfEnd IfCommand6.SetFocusEnd SubPrivate Sub Command1_KeyPress(Index As Integer, KeyAscii As Integer) If KeyAscii = 13 Then KeyAscii = 0End SubPrivate Sub Command2_Click(Index As Integer)soundbz = Falsemand = "Close"If Index = 0 Then MMControl1.FileName = ProgramPath & "/声音文件/加.wav"If Index = 1 Then MMControl1.FileName = ProgramPath & "/声音文件/减.wav"If Index = 3 Then MMControl1.FileName = ProgramPath & "/声音文件/乘.wav"If Index = 2 Then MMControl1.FileName = ProgramPath & "/声音文件/除.wav"If Index = 4 ThenMMControl1.FileName = ProgramPath & "/声音文件/等于.wav"soundbz = TrueEnd Ifmand = "Open"mand = "Play"If opnre = 0 Or Index = 4 ThenIf ind = 0 Thenprev = prev + Val(text1.Caption)ElseIf ind = 1 Thenprev = prev - Val(text1.Caption)ElseIf ind = 2 ThenIf Val(text1.Caption) = 0 Thentext1 = "错误!"BeepCommand6.SetFocusExit SubElseprev = prev / Val(text1.Caption)End IfElseIf ind = 3 Thenprev = prev * Val(text1.Caption)End Iftext1.Caption = Str(prev)oflag = 0End Ifopnre = 1ind = Indexdflag = 0Command6.SetFocusIf Index = 4 ThenIf Option1.Value = True Then text1 = Trim(Round(text1, 2))If Option2.Value = True Then text1 = Trim(Round(text1, 3))If Option3.Value = True Then text1 = Trim(Round(text1, 4))If Option4.Value = True Then text1 = Trim(text1)If text1 <> 0 ThenText = Mid(text1, 1, 1)If Text = "." Thentext1 = "0" & text1End IfEnd Ifls = Len(text1)If ls <> 0 ThenFor I = 1 To lst = Mid(text1, I, 1)DoEventsDo While (MMControl1.Mode <> 525) And soundbzDoEventsLoopmand = "Close"If t <> "." ThenIf t = "-" ThenMMControl1.FileName = ProgramPath & "/声音文件/负.wav"ElseMMControl1.FileName = ProgramPath & "/声音文件/" & t & ".wav"End IfElseMMControl1.FileName = ProgramPath & "/声音文件/10.wav"End Ifmand = "Open"mand = "Play"Next IEnd IfEnd IfEnd SubPrivate Sub Command2_KeyPress(Index As Integer, KeyAscii As Integer) If KeyAscii = 13 Then KeyAscii = 0End SubPrivate Sub Command3_Click()soundbz = Falsemand = "Close"MMControl1.FileName = ProgramPath & "/声音文件/归零.wav"mand = "Open"mand = "Play"text1.Caption = " 0"Command6.SetFocusEnd SubPrivate Sub Command3_KeyPress(KeyAscii As Integer)If KeyAscii = 13 Then KeyAscii = 0End SubPrivate Sub Command4_Click()soundbz = Falsemand = "Close"MMControl1.FileName = ProgramPath & "/声音文件/清除.wav"mand = "Open"mand = "Play"dflag = 0prev = 0oflag = 0ind = 0opnre = 0text1.Caption = " 0"Command6.SetFocusEnd SubPrivate Sub Command4_KeyPress(KeyAscii As Integer)If KeyAscii = 13 Then KeyAscii = 0End SubPrivate Sub Command5_Click()soundbz = FalseSaveSetting App.EXEName, "保留", "n1", Option1.Value SaveSetting App.EXEName, "保留", "n2", Option2.Value SaveSetting App.EXEName, "保留", "n3", Option3.Value SaveSetting App.EXEName, "保留", "n4", Option4.Value SaveSetting App.EXEName, "置顶", "yorn", Check1.Value ' mand = "Close"Unload MeEnd SubPrivate Sub Command5_KeyPress(KeyAscii As Integer) If KeyAscii = 13 Then KeyAscii = 0End SubPrivate Sub Command6_Click()Command2_Click (4)End SubPrivate Sub Form_KeyPress(KeyAscii As Integer)If text1 = "错误!" ThenCommand4_ClickEnd IfIf KeyAscii = Asc(".") ThenI = 10Command1_Click (I)ElseIf KeyAscii = Asc("0") ThenI = 0Command1_Click (I)ElseIf KeyAscii = Asc("1") ThenI = 1Command1_Click (I)ElseIf KeyAscii = Asc("2") ThenI = 2Command1_Click (I)ElseIf KeyAscii = Asc("3") ThenI = 3Command1_Click (I)ElseIf KeyAscii = Asc("4") ThenI = 4Command1_Click (I)ElseIf KeyAscii = Asc("5") ThenI = 5Command1_Click (I)ElseIf KeyAscii = Asc("6") ThenI = 6Command1_Click (I)ElseIf KeyAscii = Asc("7") ThenI = 7Command1_Click (I)ElseIf KeyAscii = Asc("8") ThenI = 8Command1_Click (I)ElseIf KeyAscii = Asc("9") ThenI = 9Command1_Click (I)ElseIf KeyAscii = Asc("0") ThenI = 0Command1_Click (I)ElseIf KeyAscii = Asc("+") ThenI = 0Command2_Click (I) ElseIf KeyAscii = Asc("+") ThenCommand2_Click (I)ElseIf KeyAscii = Asc("-") ThenI = 1Command2_Click (I)ElseIf KeyAscii = Asc("/") ThenI = 2Command2_Click (I)ElseIf KeyAscii = Asc("*") ThenI = 3Command2_Click (I)ElseIf KeyAscii = Asc("=") Or KeyAscii = 13 ThenI = 4Command2_Click (I)ElseIf KeyAscii = Asc("c") Or KeyAscii = Asc("C") Or KeyAscii = 27 Then Command4_ClickElseIf KeyAscii = Asc("d") Or KeyAscii = Asc("D") ThenCommand3_ClickEnd IfEnd SubPrivate Sub Form_Load()If App.PrevInstance = True ThenUnload MeMsgBox "程序正在运行,不可重复运行多个!", 64, "系统提示"EndEnd Ifsoundbz = Truedflag = 0prev = 0oflag = 0ind = 0Clipboard.ClearMMControl1.DeviceType = "WaveAudio"ProgramPath = App.PathOption1.Value = GetSetting(App.EXEName, "保留", "n1", True) Option2.Value = GetSetting(App.EXEName, "保留", "n2", False) Option3.Value = GetSetting(App.EXEName, "保留", "n3", False) Option4.Value = GetSetting(App.EXEName, "保留", "n4", False) Check1.Value = GetSetting(App.EXEName, "置顶", "yorn", 0)End SubPrivate Sub Form_Unload(Cancel As Integer)mand = "Close"EndEnd SubPrivate Sub text1_Click()End Sub。
科学计算器vb代码
TabIndex = 21
Top = 2400
Width = 510
End
Begin Command1
Caption = "."
Height = 390
Index = 11
Left = 3915
TabIndex = 20
Top = 2400
Width = 510
Top = 1455
Width = 510
End
Begin Command1
Caption = "4"
Height = 390
Index = 4
Left = 2820
TabIndex = 4
Top = 1455
Width = 510
End
Begin Command1
Caption = "3"
Height = 390
End
End
End
Attribute VB_Name = "Frm_Scientific"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Caption = "*"
Height = 390
IndexLeabharlann = 1Left = 4470
TabIndex = 11
Top = 1455
Width = 510
End
VB 计算器 代码
VB 计算器代码==表单控件设置================================================数字用了一个控件数组(cmdN),+-*/也用了一个控件数组(cmdY),小数点cmdP,"="cmdE,"C"(清除所有)cmdC,"CE"(清除当前数)cmdCE,Breakspace(清除最后一个输入的数)cmdCELast,输出是Test1所有按钮TabStop = False将Text1.locked = .T.==代码部分====================================================Option ExplicitDim dblN(0 To 1) As Double '用于计算的数Dim dblM As Double '记忆数值Dim blnP As Boolean '小数点Dim bytY As Byte '运算符Private Sub cmdCE1_Click() '清除输入的最后一个键Me.Text1.Text = dblN(1)dblN(1) = CDbl(Left(Me.Text1.Text, Len(Me.Text1.Text) - 1))Me.Text1.Text = dblN(1)End SubPrivate Sub cmdCE_Click() '清除输入的这个数值dblN(1) = 0Me.Text1.Text = dblN(1)End SubPrivate Sub cmdCELast_Click()Me.Text1.Text = dblN(1)If Len(Me.Text1.Text) = 1 ThendblN(1) = 0ElsedblN(1) = CDbl(Left(Me.Text1.Text, Len(Me.Text1.Text) - 1))End IfMe.Text1.Text = dblN(1)End SubPrivate Sub cmdE_Click() '计算结果On Error GoTo errSelect Case bytYCase Is = 0dblN(0) = dblN(0) + dblN(1)Case Is = 1dblN(0) = dblN(0) - dblN(1)Case Is = 2dblN(0) = dblN(0) * dblN(1)Case Is = 3dblN(0) = dblN(0) / dblN(1)End SelectMe.Text1.Text = dblN(0)If Left(Me.Text1.Text, 1) = "." Then Me.Text1.Text = "0" + Me.Text1.Text bytY = 0dblN(1) = 0blnP = FalseExit Suberr:Me.Text1.Text = "错误:" & Error(err.Number)bytY = 0dblN(1) = 0: dblN(0) = 0blnP = FalseEnd SubPrivate Sub cmdN_Click(Index As Integer) '数字输入If Not blnP ThendblN(1) = dblN(1) * 10 + IndexElseIf InStr(CStr(dblN(1)), ".") > 0 ThendblN(1) = Val(CStr(dblN(1)) + CStr(Index))ElsedblN(1) = dblN(1) + Index / 10End IfEnd IfMe.Text1.Text = dblN(1)If Left(Me.Text1.Text, 1) = "." Then Me.Text1.Text = "0" + Me.Text1.Text End SubPrivate Sub cmdP_Click() '小数点输入blnP = TrueEnd SubPrivate Sub cmdY_Click(Index As Integer) '运算符输入Call cmdE_ClickbytY = IndexEnd SubPrivate Sub cmdC_Click() '归零bytY = 0dblN(1) = 0: dblN(0) = 0blnP = FalseMe.Text1.Text = dblN(1)End SubPrivate Sub Text1_KeyUp(KeyCode As Integer, Shift As Integer)'处理键盘输入数值Select Case KeyCodeCase 96 To 105, 48 To 57If Shift = 0 Then Call cmdN_Click(KeyCode - IIf(KeyCode >= 96, 96, 48)) '数字输入If Shift = 1 And KeyCode = 56 Then Call cmdY_Click(2) '大键盘上档*Case 110, 190 '小数点If Shift = 0 Then Call cmdP_ClickCase Is = 107, 187 '+Call cmdY_Click(0)Case 109, 189 '-Call cmdY_Click(1)Case Is = 106 '小键盘*Call cmdY_Click(2)Case 111, 191 '/Call cmdY_Click(3)Case Is = 13 '回车(=)Call cmdE_ClickCase Is = 187If Shift = 1 ThenCall cmdY_Click(0) '大键盘上档+ElseCall cmdE_Click '大键盘=End IfCase Is = 27 'CCall cmdC_ClickEnd SelectEnd SubPrivate Sub Text1_Validate(Cancel As Boolean) '焦点一直在text1Me.Text1.SetFocusEnd Sub。
使用VB制作计算器程序
多功能计算器界面如下图所示。
实现代码如下:Public b As SinglePublic flag, first As IntegerDim narray(100) As Single '存放文本框1中输入的多个数据Dim i As Integer '存放输入数组的实际长度'单次运算Dim a As Single '存放第一个操作数Dim key As String '存放运算符'以上在模块中定义变量Private Sub cmd0_Click() '单击数字键0Text1.Text = Text1.Text + cmd0.Caption '可用"&"代替"+"End SubPrivate Sub cmd1_Click() '单击数字键1Text1.Text = Text1.Text + cmd1.CaptionEnd SubPrivate Sub cmd2_Click() '单击数字键2Text1.Text = Text1.Text + cmd2.CaptionEnd SubPrivate Sub cmd3_Click() '单击数字键3Text1.Text = Text1.Text + cmd3.CaptionEnd SubPrivate Sub cmd4_Click() '单击数字键4Text1.Text = Text1.Text + cmd4.CaptionEnd SubPrivate Sub cmd5_Click() '单击数字键5Text1.Text = Text1.Text + cmd5.CaptionEnd SubPrivate Sub cmd6_Click() '单击数字键6Text1.Text = Text1.Text + cmd6.CaptionEnd SubPrivate Sub cmd7_Click() '单击数字键7Text1.Text = Text1.Text + cmd7.CaptionEnd SubPrivate Sub cmd8_Click() '单击数字键8Text1.Text = Text1.Text + cmd8.CaptionEnd SubPrivate Sub cmd9_Click() '单击数字键9Text1.Text = Text1.Text + cmd9.CaptionEnd SubPrivate Sub cmddot_Click() '连接小数点Text1.Text = Text1.Text + cmddot.CaptionIf InStr(Text1.Text, ".") < Len(Text1.Text) Then'防止出现多个小数点Text1.Text = Left(Text1.Text, Len(Text1.Text) - 1)End IfEnd SubPrivate Sub cmdcls_Click() '单击CE键Text1.Text = ""End SubPrivate Sub add_Click() '单击“+”,保存第一个操作数和运算符 a = Val(Text1.Text)key = add.CaptionText1.Text = " "End SubPrivate Sub subs_Click() '单击“-”a = Val(Text1.Text)key = subs.CaptionText1.Text = " "End SubPrivate Sub mul_Click() '单击“*”a = Val(Text1.Text)key = mul.CaptionText1.Text = " "End SubPrivate Sub div_Click() '单击“/”a = Val(Text1.Text)key = div.CaptionText1.Text = " "End SubPrivate Sub modi_Click() '单击“Mod”a = Val(Text1.Text)key = more.CaptionText1.Text = " "End SubPrivate Sub mulpi_Click() '单击“^”a = Val(Text1.Text)key = mulpi.CaptionText1.Text = " "End SubPrivate Sub sign_Click() '单击“+/-”,改变操作数符号Text1.Text = -Val(Text1.Text)End SubPrivate Sub equal_Click() '单击“=”Select Case key '判断运算符Case "+": Text1.Text = a + Val(Text1.Text)Case "-": Text1.Text = a - Val(Text1.Text)Case "*": Text1.Text = a * Val(Text1.Text)Case "/": Text1.Text = a / Val(Text1.Text)Case "\": Text1.Text = a \ Val(Text1.Text)Case "mod": Text1.Text = a Mod Val(Text1.Text)Case "^": Text1.Text = a ^ Val(Text1.Text)Case "<": Text1.Text = a < Val(Text1.Text)Case ">": Text1.Text = a > Val(Text1.Text)Case "<>": Text1.Text = a <> Val(Text1.Text)Case "Like": b = "*" & Trim(Text1.Text) & "*"If (Str(a) Like b) Then Text1.Text = True Else Text1.Text = False Case "Not": Text1.Text = Not aCase "And": Text1.Text = a And Val(Text1.Text)Case "Or": Text1.Text = a Or Val(Text1.Text)Case "Xor": Text1.Text = a Xor Val(Text1.Text)End SelectEnd SubPrivate Sub less_Click() '单击“<”a = Val(Text1.Text)key = less.CaptionText1.Text = " "End SubPrivate Sub more_Click() '单击“>”a = Val(Text1.Text)key = more.CaptionText1.Text = " "End SubPrivate Sub notequal_Click() '单击“<>”a = Val(Text1.Text)key = notequal.CaptionText1.Text = " "End SubPrivate Sub likes_Click() '单击“Likes”a = Val(Text1.Text)key = likes.CaptionText1.Text = " "End SubPrivate Sub cmdnot_Click() '单击“Not”a = Val(Text1.Text)key = cmdnot.CaptionText1.Text = " "End SubPrivate Sub cmdand_Click() '单击“And”a = Val(Text1.Text)key = cmdand.CaptionText1.Text = " "End SubPrivate Sub cmdor_Click() '单击“Or”a = Val(Text1.Text)key = cmdor.CaptionText1.Text = " "End SubPrivate Sub cmdxor_Click() '单击“Xor”a = Val(Text1.Text)key = cmdxor.CaptionText1.Text = " "End SubPrivate Sub Command3_Click(Index As Integer) '函数区中功能实现,Command3'为函数区控件数组名Select Case IndexCase 0Text2.Text = Sin(Val(Trim$(Text1.Text))) '调用内部函数sinCase 1Text2.Text = Cos(Val(Trim$(Text1.Text)))Case 2Text2.Text = Abs(Val(Trim$(Text1.Text)))Case 3Text2.Text = Sqr(Val(Trim$(Text1.Text)))Case 4Text2.Text = Hex$(Val(Trim$(Text1.Text)))Case 5Text2.Text = Oct$(Val(Trim$(Text1.Text)))Case 6Text2.Text = Asc(Trim$(Text1.Text))Case 7Text2.Text = Rnd(Val(Trim$(Text1.Text)))Case 8Text2.Text = DateCase 9Text2.Text = Len(Trim$(Text1.Text))Case 10Text2.Text = sum1() '调用自定义函数求和Case 11Text2.Text = ave() '调用自定义函数求平均值Case 12 '12为max命令按钮的控件数组Index值Dim m As SingleCall max2(m) '调用自定义子过程求最大值Text2.Text = m 'm为调用过程得到的最大值'Text2.Text = max() '调用自定义函数过程求最大值Case 13Text2.Text = min() '调用自定义函数过程求最小值Case 14Text2.Text = sort() '调用自定义函数过程排序Case 15'Text2.Text = fac() '调用自定义函数过程求阶乘Text2.Text = fac1(Val(Text1.Text))'调用自定义函数过程求阶乘,用递归实现End SelectEnd SubPrivate Function sum1()Dim k As IntegerDim s As Singles = 0For k = 1 To i - 1s = s + narray(k)Next ksum1 = sEnd FunctionPrivate Function max()Dim k As IntegerDim s As Single, m As Singlem = narray(1)For k = 2 To iIf m < narray(k) Then m = narray(k) Next kmax = mEnd FunctionPrivate Function ave() '求平均值Dim k As IntegerDim s As Single, m As SingleFor k = 1 To is = s + narray(k)Next kave = s / (i - 1)End FunctionPrivate Function min() '求最小值函数Dim k As IntegerDim s As Single, m As Singlem = narray(1)For k = 2 To i - 1If m > narray(k) Then m = narray(k) Next kmin = mEnd FunctionPrivate Function sort() '排序函数Dim k As Integer, j As IntegerDim s As String, m As SingleFor k = 1 To i - 2For j = 1 To i - 1If narray(j) < narray(j + 1) Thenm = narray(j)narray(j) = narray(j + 1)narray(j + 1) = mEnd IfNext jNext kFor k = 1 To i - 1s = s+" "+Str$(narray(k)) '将排序结果存放到字符串s,以便带回到主调程序中Next ksort = sEnd FunctionPrivate Function fac() '求阶乘函数Dim k As Integer, j As IntegerDim m As SingleIf InStr(Trim$(Text1.Text), " ") > 1 Then'如果在文本输入框中输入了多个数据,则计算一个'数据的阶乘j = first '数组元素narray()中第一个元素Else: j = Val(Trim$(Text1.Text))End Ifm = 1For k = 1 To jm = m * kNext kfac = mEnd FunctionPrivate Sub Text1_KeyPress(Keyasc As Integer)'在文本框1中输入多个数据,以空格分隔,按回'车键结束,识别数据存放到数组narray( )中Dim c As StringDim n As Integer, k As Integeri = 1k = 1If Keyasc = 13 Then '按下回车键For n = 0 To Len(Text1.Text) - 1c = Mid$(Text1.Text, n + 1, 1)If c = " " Thennarray(i) = Val(Mid$(Text1.Text, k, n - k + 1))'识别数据存放在数组narray(i)中k = k + Len(Str$(narray(i))) '下一个数据位置起点i = i + 1 '每识别一个数据数组实际长度加1End IfNext nEnd Iffirst = narray(1)End SubPrivate Sub max2(m As Single) '求数组元素的最大值Dim k As Integerm = narray(1)For k = 2 To iIf m < narray(k) Then m = narray(k)Next kEnd SubPrivate Function fac1(n As Long) '递归求阶乘If n > 1 Thenfac1 = fac1(n - 1) * nElsef ac1 = 1End IfEnd Function。
VB简易计算器代码
Public Class Form1Dim OperatorState As IntegerDim data1 As IntegerDim result As IntegerDim data2 As Integer’下面是0~9十个按钮的点击事件Private Sub Button1_Click(ByVal sender As , ByVal e As Handles = + "1"End SubPrivate Sub Button2_Click(ByVal sender As , ByVal e As Handles = + "2"End SubPrivate Sub Button3_Click(ByVal sender As , ByVal e As Handles = + "3"End SubPrivate Sub Button4_Click(ByVal sender As , ByVal e As Handles = + "4"End SubPrivate Sub Button5_Click(ByVal sender As , ByVal e As Handles = + "5"End SubPrivate Sub Button6_Click(ByVal sender As , ByVal e As Handles = + "6"End SubPrivate Sub Button7_Click(ByVal sender As , ByVal e As Handles = + "7"End SubPrivate Sub Button8_Click(ByVal sender As , ByVal e As Handles = + "8"End SubPrivate Sub Button9_Click(ByVal sender As , ByVal e As Handles = + "9"End SubPrivate Sub Button10_Click(ByVal sender As , ByVal e As Handles = + "0"End Sub’下面是清除键的代码Private Sub Button15_Click(ByVal sender As , ByVal e As Handles = ""End Sub’下面是加减乘除四个按钮的代码Private Sub Button11_Click(ByVal sender As , ByVal e As Handles data1 = ValOperatorState = 1= ""End SubPrivate Sub Button12_Click(ByVal sender As , ByVal e As Handlesdata1 = ValOperatorState = 2= ""End SubPrivate Sub Button13_Click(ByVal sender As , ByVal e As Handles data1 = ValOperatorState = 3= ""End SubPrivate Sub Button14_Click(ByVal sender As , ByVal e As Handles data1 = ValOperatorState = 4= ""End Sub’下面是等于号的的代码Private Sub Button16_Click(ByVal sender As , ByVal e As Handlesdata2 = ValIf (OperatorState = 1) Thenresult = data1 + data2End IfIf (OperatorState = 2) Thenresult = data1 - data2End IfIf (OperatorState = 3) Thenresult = data1 * data2End IfIf (OperatorState = 4) Then result = data1 / data2End If= Str(result)End SubEnd Class。
用VB编写一个简单计算器
用VB编写一个简单计算器一、功能:实现简单的加减乘除功能,C归零,CE取消输入,%计算并显示第一个操作数的百分比。
二、控件:1个label,20个commandbutton。
三、计算器运行界面:四、详细代码:Option ExplicitDim Op1, Op2 '前面输入的操作数Dim DecimalFlag As Integer '小数点仍然存在吗?Dim NumOps As Integer '操作数个数Dim LastInput '指示上一次按键事件的类型Dim OpFlag '指示未完成的操作Dim TempReadout' C (取消) 按钮的Click 事件过程' 重新设置显示并初始化变量Private Sub Cancel_Click()Readout = Format(0, "0.")Op1 = 0Op2 = 0Form_LoadEnd Sub' CE (取消输入) 按钮的Click 事件过程Private Sub CancelEntry_Click()Readout = Format(0, "0.")DecimalFlag = FalseLastInput = "CE"End Sub' 小数点(.) 按钮的Click 事件过程' 如果上一次按键为运算符,初始化readout 为"0.";' 否则显示时追加一个小数点Private Sub Decimal_Click()If LastInput = "NEG" ThenReadout = Format(0, "-0.")ElseIf LastInput <> "NUMS" ThenReadout = Format(0, "0.")End IfDecimalFlag = TrueLastInput = "NUMS"End Sub' 窗体的初始化过程' 设置所有变量为其初始值Private Sub Form_Load()DecimalFlag = FalseNumOps = 0LastInput = "NONE"OpFlag = " "Readout = Format(0, "0.")'Decimal.Caption = Format(0, ".")End Sub' 数字键(0-9) 的Click 事件过程' 向显示中的数追加新数Private Sub Number_Click(Index As Integer)If LastInput <> "NUMS" ThenReadout = Format(0, ".")DecimalFlag = FalseEnd IfIf DecimalFlag ThenReadout = Readout + Number(Index).CaptionElseReadout = Left(Readout, InStr(Readout, Format(0, ".")) - 1) + Number(Index).Caption + Format(0, ".")End IfIf LastInput = "NEG" Then Readout = "-" & ReadoutLastInput = "NUMS"End Sub' 运算符(+, -, x, /, =) 的Click 事件过程' 如果接下来的按键是数字键,增加NumOps。
VB计算器程序代码
Public Class Form1Public zt As IntegerPublic fh As IntegerPublic x, y As SinglePrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Loadzt = 1fh = 0TextBox1.Text = 0x = 0y = 0End SubPrivate Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.ClickIf zt = 1 ThenTextBox1.Text = TextBox1.Text * 10 + 1zt = 2ElseIf zt = 2 ThenTextBox1.Text = TextBox1.Text * 10 + 1ElseIf zt = 3 ThenTextBox1.Text = 1zt = 4ElseIf zt = 4 ThenTextBox1.Text = TextBox1.Text * 10 + 1End IfEnd SubPrivate Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.ClickIf zt = 1 ThenTextBox1.Text = TextBox1.Text * 10 + 2zt = 2ElseIf zt = 2 ThenTextBox1.Text = TextBox1.Text * 10 + 2ElseIf zt = 3 ThenTextBox1.Text = 2zt = 4ElseIf zt = 4 ThenTextBox1.Text = TextBox1.Text * 10 + 2End IfEnd SubPrivate Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.ClickIf zt = 1 ThenTextBox1.Text = TextBox1.Text * 10 + 3zt = 2ElseIf zt = 2 ThenTextBox1.Text = TextBox1.Text * 10 + 3ElseIf zt = 3 ThenTextBox1.Text = 3zt = 4ElseIf zt = 4 ThenTextBox1.Text = TextBox1.Text * 10 + 3End IfEnd SubPrivate Sub Button11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button11.ClickIf zt = 2 Thenx = TextBox1.Textfh = 1zt = 3ElseIf zt = 3 Thenfh = 1End IfEnd SubPrivate Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.ClickIf zt = 2 Thenx = TextBox1.Textfh = 3zt = 3ElseIf zt = 3 Thenfh = 3End IfEnd SubPrivate Sub Button12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button12.ClickIf zt = 2 Thenx = TextBox1.Textfh = 2zt = 3ElseIf zt = 3 Thenfh = 2End IfEnd SubPrivate Sub Button14_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button14.ClickIf zt = 2 Thenx = TextBox1.Textfh = 4zt = 3ElseIf zt = 3 Thenfh = 4End IfEnd SubPrivate Sub Button15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button15.Clickx = 0y = 0TextBox1.Text = 0fh = 0zt = 1End SubPrivate Sub Button16_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button16.ClickIf zt = 4 Theny = TextBox1.TextIf fh = 1 ThenTextBox1.Text = x + yElseIf fh = 2 ThenTextBox1.Text = x - yElseIf fh = 3 ThenTextBox1.Text = x * yElseIf fh = 4 ThenTextBox1.Text = x / yEnd IfEnd IfPrivate Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.ClickIf zt = 1 ThenTextBox1.Text = TextBox1.Text * 10 + 4zt = 2ElseIf zt = 2 ThenTextBox1.Text = TextBox1.Text * 10 + 4ElseIf zt = 3 ThenTextBox1.Text = 4zt = 4ElseIf zt = 4 ThenTextBox1.Text = TextBox1.Text * 10 + 4End IfEnd SubPrivate Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.ClickIf zt = 1 ThenTextBox1.Text = TextBox1.Text * 10 + 5zt = 2ElseIf zt = 2 ThenTextBox1.Text = TextBox1.Text * 10 + 5ElseIf zt = 3 ThenTextBox1.Text = 5zt = 4ElseIf zt = 4 ThenTextBox1.Text = TextBox1.Text * 10 + 5End IfEnd SubPrivate Sub Button6_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button6.ClickIf zt = 1 ThenTextBox1.Text = TextBox1.Text * 10 + 6zt = 2ElseIf zt = 2 ThenTextBox1.Text = TextBox1.Text * 10 + 6ElseIf zt = 3 ThenTextBox1.Text = 6zt = 4ElseIf zt = 4 ThenTextBox1.Text = TextBox1.Text * 10 + 6End SubPrivate Sub Button7_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button7.ClickIf zt = 1 ThenTextBox1.Text = TextBox1.Text * 10 + 7zt = 2ElseIf zt = 2 ThenTextBox1.Text = TextBox1.Text * 10 + 7ElseIf zt = 3 ThenTextBox1.Text = 7zt = 4ElseIf zt = 4 ThenTextBox1.Text = TextBox1.Text * 10 + 7End IfEnd SubPrivate Sub Button8_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button8.ClickIf zt = 1 ThenTextBox1.Text = TextBox1.Text * 10 + 8zt = 2ElseIf zt = 2 ThenTextBox1.Text = TextBox1.Text * 10 + 8ElseIf zt = 3 ThenTextBox1.Text = 8zt = 4ElseIf zt = 4 ThenTextBox1.Text = TextBox1.Text * 10 + 8End IfEnd SubPrivate Sub Button9_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button9.ClickIf zt = 1 ThenTextBox1.Text = TextBox1.Text * 10 + 9zt = 2ElseIf zt = 2 ThenTextBox1.Text = TextBox1.Text * 10 + 9ElseIf zt = 3 ThenTextBox1.Text = 9zt = 4ElseIf zt = 4 ThenTextBox1.Text = TextBox1.Text * 10 + 9End IfEnd SubPrivate Sub Button10_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button10.ClickIf zt = 1 ThenTextBox1.Text = TextBox1.Text * 10 + 0zt = 2ElseIf zt = 2 ThenTextBox1.Text = TextBox1.Text * 10 + 0ElseIf zt = 3 ThenTextBox1.Text = 0zt = 4ElseIf zt = 4 ThenTextBox1.Text = TextBox1.Text * 10 + 0End IfEnd SubEnd Class。
VB计算器程序代码
VB计算器程序代码下面是一个简单的VB计算器程序代码,可以进行基本的四则运算:```VBImports System.MathPublic Class Form1Dim num1, num2, result As DoubleDim operatorType As String = ""Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.LoadEnd SubPrivate Sub Button_Click(sender As Object, e As EventArgs) Handles btn0.Click, btn1.Click, btn2.Click, btn3.Click,btn4.Click, btn5.Click, btn6.Click, btn7.Click, btn8.Click, btn9.Click, btnDot.ClickDim button As Button = CType(sender, Button)If button.Text = "." ThenIf Not txtDisplay.Text.Contains(".") ThentxtDisplay.Text += button.TextEnd IfElsetxtDisplay.Text += button.TextEnd IfEnd SubPrivate Sub Operator_Click(sender As Object, e As EventArgs) Handles btnAdd.Click, btnSubtract.Click, btnMultiply.Click, btnDivide.ClickDim button As Button = CType(sender, Button)num1 = CDbl(txtDisplay.Text)operatorType = button.TexttxtDisplay.ClearEnd SubPrivate Sub btnEquals_Click(sender As Object, e As EventArgs) Handles btnEquals.Clicknum2 = CDbl(txtDisplay.Text)Select Case operatorTypeCase "+"result = num1 + num2Case "-"result = num1 - num2Case "*"result = num1 * num2Case "/"If num2 <> 0 Thenresult = num1 / num2ElseMessageBox.Show("除数不能为零!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)End IfEnd SelecttxtDisplay.Text = result.ToStringEnd SubPrivate Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.ClicktxtDisplay.ClearEnd SubPrivate Sub btnSqrt_Click(sender As Object, e As EventArgs) Handles btnSqrt.ClickIf txtDisplay.Text = "" ThenMessageBox.Show("请输入一个数字!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)Elsenum1 = CDbl(txtDisplay.Text)result = Sqrt(num1)txtDisplay.Text = result.ToStringEnd IfEnd SubPrivate Sub btnPower_Click(sender As Object, e As EventArgs) Handles btnPower.ClickIf txtDisplay.Text = "" ThenMessageBox.Show("请输入一个数字!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error)Elsenum1 = CDbl(txtDisplay.Text)result = num1 ^ 2txtDisplay.Text = result.ToStringEnd IfEnd SubPrivate Sub btnBackspace_Click(sender As Object, e As EventArgs) Handles btnBackspace.ClickIf txtDisplay.Text.Length > 0 ThentxtDisplay.Text = txtDisplay.Text.Substring(0, txtDisplay.Text.Length - 1)End IfEnd SubPrivate Sub btnNegative_Click(sender As Object, e As EventArgs) Handles btnNegative.ClickIf txtDisplay.Text.Length > 0 ThenIf txtDisplay.Text.Substring(0, 1) = "-" ThentxtDisplay.Text = txtDisplay.Text.Substring(1, txtDisplay.Text.Length - 1)ElsetxtDisplay.Text = "-" + txtDisplay.TextEnd IfEnd IfEnd SubEnd Class```这个计算器程序具有以下功能:1.支持0-9的数字输入和小数点的输入。
VB计算器代码
Private Sub a_KeyPress(KeyAscii As Integer) '限制输入非数字,a为输入框初始值为空
If KeyAscii = 46 And Not CBool(InStr(a, ".")) Then Exit Sub '限制只能输入一个小数点
If InStr(a, "0.") = 1 Then Exit Sub '限制小数点前只能输入一个0
If InStr(a, "0") = 1 Then a.Text = "" '限制数字前输入0
End Sub
Private Sub back_Click() '退格功能
a.SetFocus
SendKeys "{7}"
End Sub
Private Sub key8_Click()
a.SetFocus
SendKeys "{8}"
End Sub
Private Sub key9_Click()
a.SetFocus
SendKeys "{9}"
End Sub
Private Sub add_Click() '按下+号功能
a.SetFocus
SendKeys "{2}"
End Sub
Private Sub key3_Click()
a.SetFocus
SendKeys "{3}"
VB计算器代码
Dim num1 As Single '定义第一个操作数变量,用来临时保存用户所输入的被加数,被减数等Dim num2 As Single '定义第二个操作数变量,用来临时保存用户所输入的加数,减数等Dim oper As Byte '定义一个标记变量,用来临时记录用户所按下的运算符,并规定1代表加,2代表减,3代表乘,4代表除Private Sub Command1_Click() '当1按钮被单击时,则执行以下命令Text1.Text = Me.Text1.Text + "1" '如果用户按下1,则在文本框中添加数字1End SubPrivate Sub Command10_Click()Text1.Text = Me.Text1.Text + "0" '如果用户按下0,则在文本框中添加数字0End SubPrivate Sub Command11_Click()Text1.Text = Me.Text1.Text + "." '如果用户按下".",则在文本框中添加小数点"."End SubPrivate Sub Command12_Click() '当等号按钮被鼠标单击时,则执行以下命令Dim result As Single '定义结果变量,用来临时保存计算结果num2 = Val(Text1.Text) ' 将文本框中用户所输入的字符转变成数值,并赋值给第二个操作数变量If oper = 1 Then result = num1 + num2 '如果先前记录用户所按下的是加法运算符,则执行加法运算,并把运算结果赋值给结果变量ResultIf oper = 2 Then result = num1 - num2 '如果先前记录用户所按下的是减法运算符,则执行减法运算,并把运算结果赋值给结果变量ResultText1.Text = "" '清空文本框中的数值Text1.Text = result '将计算结果显示在文本框中End SubPrivate Sub Command13_Click() '当加号按钮被单击时,则执行以下命令num1 = Val(Text1.Text) ' 将文本框中用户所输入的字符转变成数值,并赋值给第一个操作数变量oper = 1 '用标记变量oper临时记录用户所按下的运算符,用1代表加法Text1.Text = "" '清空文本框中的数值,即被加数的值End SubPrivate Sub Command14_Click()num1 = Val(Text1.Text) ' 将文本框中用户所输入的字符转变成数值,并赋值给第一个操作数变量oper = 2 '用标记变量oper临时记录用户所按下的运算符,用2代表减法Text1.Text = "" '清空文本框中的数值,即被减数的值End SubPrivate Sub Command15_Click()Text1.Text = "" '清除文本框中的内容End SubPrivate Sub Command2_Click()Text1.Text = Me.Text1.Text + "2"End SubPrivate Sub Command3_Click()Text1.Text = Me.Text1.Text + "3"End SubPrivate Sub Command4_Click()Text1.Text = Me.Text1.Text + "4"End SubPrivate Sub Command5_Click() Text1.Text = Me.Text1.Text + "5" End SubPrivate Sub Command6_Click() Text1.Text = Me.Text1.Text + "6" End SubPrivate Sub Command7_Click() Text1.Text = Me.Text1.Text + "7" End SubPrivate Sub Command8_Click() Text1.Text = Me.Text1.Text + "8" End SubPrivate Sub Command9_Click() Text1.Text = Me.Text1.Text + "9" End Sub。
VB实例代码-计算器
VB实例代码-计算器首先,需建立如下控件:标签:Label1命令按钮:名称 Caption值Cback ?Cclear CECstart CCsin SinCcos CosCsqrt SqrtCsign +/-Cpoint CpointCequal =控件数组:(命令按钮)Calcu(1) +Calcu(2) -Calcu(3) *Calcu(4) /Cnum(0) 0Cnum(1) 1...Cnum(9) 9然后在代码窗口写源码:Option ExplicitDim Num1, Num2 As Double Dim PointIn As Boolean Dim Inputing As Boolean Dim Operation1 As IntegerPrivate Sub Calcu_Click(i As Integer)If Inputing = False Then '在前次运算提交之后尚未输入新的数据Operation1 = i '运算符重置Num1 = Label1 '将显示栏里的数据赋值给第一个操作数Exit SubEnd IfInputing = False '将当前状态置为非输入数据阶段If Num1 <> 0 Then '非首次计算Num2 = Label1 '将显示栏里的数据赋值给第二个操作数Calculate (Operation1) '计算前一次运算并显示结果Else '首次计算Num1 = Label1 '将显示栏里的数据赋值给第一个操作数End IfOperation1 = i '提交运算符End SubPrivate Sub Cback_Click()Dim TheLen As IntegerTheLen = Len(Label1)If TheLen > 2 ThenIf Right(Label1, 1) = "." ThenLabel1 = Left(Label1, TheLen - 2) & "."ElseLabel1 = Left(Label1, TheLen - 1)End IfElseCclear_ClickEnd IfEnd SubPrivate Sub Cclear_Click()Label1 = "0."Num2 = 0PointIn = FalseEnd SubPrivate Sub Ccos_Click()Calculate (6)Inputing = FalseEnd SubPrivate Sub Cequal_Click()If Inputing Then '如果刚输入过数据'Or Operation1 > 0 Then Num2 = Label1 '将显示栏里的数据赋值给第二个操作数End IfInputing = False '将当前状态置为非输入数据阶段Calculate (Operation1) '计算提交的运算并显示结果Num1 = 0Operation1 = 0End SubPrivate Sub Calculate(Oprt As Integer) Select Case OprtCase 1Num1 = Num1 + Num2ShowResult (Num1)Case 2Num1 = Num1 - Num2ShowResult (Num1)Case 3Num1 = Num1 * Num2ShowResult (Num1)Case 4Num1 = Num1 / Num2ShowResult (Num1)Case 5Num2 = Label1Num1 = Sin(Num2)ShowResult (Num1)Case 6Num2 = Label1Num1 = Cos(Num2)ShowResult (Num1)Case 7Num2 = Label1Num1 = Sqr(Num2)ShowResult (Num1)End SelectEnd SubPrivate Sub ShowResult(Num As Double)If Num = Fix(Num) Then '整数Label1 = Num & "."ElseIf Left(Num, 1) = "." Then '第一个字符为小数点Label1 = "0" & NumElseIf Left(Num, 2) = "-." Then '前两个字符为"-." Label1 = "-0." & Right(CStr(Num), Len(CStr(Num)) - 2) ElseLabel1 = NumEnd IfEnd SubPrivate Sub Cnum_Click(Index As Integer)NumInput (Index)End SubPrivate Sub Cpoint_Click()If Inputing = False ThenLabel1 = "0."Inputing = TrueEnd IfPointIn = TrueEnd SubPrivate Sub Csign_Click()If Label1 <> "0." ThenDim StrTemp As StringStrTemp = Label1If Left(StrTemp, 1) = "-" ThenLabel1 = Right(StrTemp, Len(StrTemp) - 1) ElseLabel1 = "-" & StrTempEnd IfEnd IfEnd SubPrivate Sub Csin_Click()Calculate (5)Inputing = FalseEnd SubPrivate Sub Csqrt_Click()Dim x As Longx = Label1If x >= 0 ThenCalculate (7)ElseLabel1 = "Error!"End IfInputing = FalseEnd SubPrivate Sub Cstart_Click()Label1 = "0."Num1 = 0Num2 = 0PointIn = FalseInputing = TrueOperation1 = 0End SubPrivate Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) Cequal.SetFocusIf KeyCode = 46 Then '按Del键Cclear_ClickEnd IfEnd SubPrivate Sub Form_KeyPress(KeyAscii As Integer)Select Case KeyAscii'键入数字:Case 48 To 57NumInput (KeyAscii - 48)Case 46 '小数点Cpoint_Click'键入运算符:Case 43 '加号Calcu_Click (1)Case 45 '减号Calcu_Click (2)Case 42 '乘号Calcu_Click (3)Case 47 '除号Calcu_Click (4)Case 27 '重新开始(退出键)Cstart_ClickCase 8 '退格Cback_ClickCase 13 '等于(回车键)Cequal_ClickEnd SelectEnd SubPrivate Sub Form_Load()Me.Top = (Screen.Height - Me.Height) / 2 Me.Left = (Screen.Width - Me.Width) / 2 Me.KeyPreview = TrueCstart_ClickEnd SubPrivate Sub NumInput(n As Integer) If Len(Label1) > 15 ThenExit SubEnd IfIf Inputing = False ThenCclear_ClickLabel1 = n & "."Inputing = TrueElseIf Label1 <> "0." ThenIf Right(Label1, 1) = "." ThenIf PointIn = False ThenDim TheLen As IntegerTheLen = Len(Label1)Label1 = Left(Label1, TheLen - 1) Label1 = Label1 & n & "."ElseLabel1 = Label1 & nEnd IfElseLabel1 = Label1 & nEnd IfElseIf PointIn ThenLabel1 = Label1 & nElseLabel1 = n & "." End IfEnd IfEnd Sub。
科学计算器vb代码
Width = 630
End
Begin mandButton Cmd_Ln
Caption = "Ln"
Height = 390
Left = 1575
TabIndex = 35
Top = 960
Width = 630
End
Begin mandButton Cmd_Square
Caption = "C"
Height = 405
Left = 4785
TabIndex = 15
Top = 405
Width = 750
End
Begin mandButton Cmd_CE
Caption = "CE"
Height = 405
Left = 3975
TabIndex = 14
Caption = "Tan"
Height = 390
Left = 120
TabIndex = 28
Top = 1935
Width = 630
End
Begin mandButton Cmd_Atan
Caption = "Atan"
Height = 390
Left = 120
TabIndex = 27
TabIndex = 17
Top = 1935
Width = 510
End
Begin mandButton Cmd_sqrt
Caption = "Sqrt"
Height = 390
Left = 5025
TabIndex = 16
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
第 3 章计算器第3 章计算器3.1 开发任务在本任务中,我们要分别实现基本算术运算、累加和计算、阶乘计算、三角函数计算、排列组合计算和对数计算等多个子任务。
3.1.1 计算器的实验版本1. 程序界面设计(1)新建工程打开VB开发环境,在工程浏览器窗口中(见图3-1左),将工程名称改为“计算器”(如图3-1中);再将窗体名称改为“frmCalculator”如图3-1右)。
图3-1 改变工程和窗体名称将窗体文件保存为“frmCalculator.frm”,工程文件保存为“prjCalculator”。
(2)添加控件在本工程中,我们需要用到下列控件:1个文本框用于输入运算数和输出结果;16个按钮构成计算器键盘,其中10个用于输入10个数字字符,1个用于输入小数点,一个用于触发计算的等号,另外4个用于选择加、减、乘、除运算符。
首先在窗体上部添加一个文本框,默认名称是Text1,调整好大小和位置(如图3-2),并将属性Text的值清空,再将对齐方式Alignment 改成“1 -Right Justify”右对齐;图3-2 添加文本框控件再来制作键盘,第1步,添加第1个按钮。
在文本框下方添加一个按钮Command1,将它调整为一个按键般大小,并把Caption属性改成“1”。
第2步,添加第2个按钮。
添加外形类似的按钮,用复制的方法即可。
不过要注意,在粘贴时VB会询问“已经有一个控件为"Command1 "。
创建一个控件数组吗?”(见图3-3),一定要回答“否”。
将复制好的按钮Command2的Caption改成2,并移动到Command1的右边。
图3-3 创建控件数组询问对话框第3步,重复进行粘贴操作,依次制作其它按钮,按图3-4的布局排列。
前9个按钮的Caption改成与它们的顺序号相同,Command10的Caption改为“0”,Command11的Caption改为“.”,ommand12的Caption改为“=”,Command13~Command16的Caption依次改为“+”、“-”、“*”、“/”。
图3-4键盘制作2. 程序代码编写(1)数字按钮的处理数字按钮的功能是,在单击按钮后,将对应的数字加入到文本框Text1中。
Private Sub Command1_Click()Text1.Text = "1"End Sub测试一下,启动程序,连续单击按钮1,文本框中只会出现1个1。
(2)错误的发现与修正赋值语句中新的数据总会替换掉原有的内容。
以下是解决办法:Private Sub Command1_Click()Text1.Text = Text1.Text & "1"End Sub下面,再来接着写Command2的事件过程代码:Private Sub Command2_Click()Text1.Text = Text1.Text & "2"End Sub仿照上述做法,再写出其它8个数字按钮和小数点按钮的单击事件过程代码。
(3)Caption的利用上述语句最后拼接的数据正好是被单击按钮的Caption。
Private Sub Command1_Click()Text1.Text = Text1.Text & Command1.Caption '输入1End SubPrivate Sub Command2_Click()Text1.Text = Text1.Text & Command2.Caption '输入2End Sub…………Private Sub Command11_Click()Text1.Text = Text1.Text & Command11.Caption '输入小数点End Sub(4)运算符按钮的处理1)运算数的暂存Dim sglNumber As Single '用于暂存第1个运算数,前缀sgl是Single 的缩写sglNumber = Text1.Text '保存第1个运算数,字符串自动转换称为单精度型如果单击加法运算符,则单击事件过程如下:Private Sub Command13_Click() '单击加法运算符按钮Dim sglNumber As Single '用于暂存第1个运算数的变量sglNumber = Text1.Text '保存第1个运算数Text1.Text = "" '用空串赋值,即可清空文本框End Sub2)加法运算代码在输入第2个运算数之后,需要单击等号按钮来完成运算。
Private Sub Command12_Click() '单击等号按钮Text1.Text = sglNumber + Val(Text1.Text) '取出第2个数与第1个数做加法并输出结果End Sub试运行程序,依次单击按钮5—加号—按钮6—等号,结果是6?调用MsgBox来找一下原因:Private Sub Command12_Click() '单击等号按钮MsgBox sglNumber '弹出变量的值Text1.Text = sglNumber + Val(Text1.Text) '做加法运算并输出End Sub对话框中弹出空串!流程再往后退,检查一下运算符按钮的单击事件过程。
Private Sub Command13_Click() '单击加法运算符按钮Dim sglNumber As SinglesglNumber = Text1.TextMsgBox sglNumber '弹出变量的值Text1.Text = ""End Sub单击加号按钮后,对话框弹出了5,运行正确,错误不在本过程。
(5)程序调试方法最基本的3种程序调试方法。
1)在适当的地方加上MsgBox调用,通过弹出变量的当前值来进行观察。
2)在适当位置加上中断标记(如图3-5),让程序运行到指定的位置暂停,然后利用中断的环境来检查变量当前的值。
图3-5 添加调试断点流程到达断点语句行时会暂时中断,将鼠标悬停在变量名上,下方就会显示“变量名=变量值”的提示(见图3-6)。
图3-6 程序中断状态下查看变量值注意,当流程暂停在中断语句处时,该语句尚未被执行。
按下【F8】键,程序可以单步执行。
3)借助于专用调试对象Debug,在适当的位置加上Debug对象的打印方法:Debug.Print <变量名列表>[;][,]在立即窗体中打印出变量的值供观察分析。
3. 变量的作用范围程序中的变量是有作用范围的,它们的作用范围与其生命周期有着密切的关系。
(1)变量的生命周期如果变量声明语句写在一个过程之内,那么,只有当程序流程进入这个过程并遇到该声明语句时,变量才会被分配内存单元,而当程序执行到EndSub语句,也就是过程结束的同时,变量就被系统从内存中清除。
在过程中声明的变量,称为过程级变量。
变量声明语句还可以写在过程之外,通常是写在模块中所有过程前面。
这种变量称为模块级变量。
模块级变量从文件被加载时出生,当文件被卸载或程序被结束时消亡。
对于窗体文件中的模块级变量来说,它们的生命与窗体的寿命一样长,只要窗体对象未被卸载,模块级变量就始终存活。
(2)变量的作用范围因为过程级变量只能在自身所在的过程之中存活,所以它们的作用范围就仅限于自身所在的过程,所以过程级变量也称局部变量。
模块级变量可以被本模块中的任何过程所访问,它的作用范围是整个模块。
对于一个模块中的所有过程而言,模块级变量就是一种全局变量。
如果模块级变量被声明为Public(公共变量),那么,在整个工程范围之内,变量都是可访问的,只是访问方法有所不同。
4. 程序代码的改进(1)加法运算代码根据变量作用范围,我们将第1个运算数的暂存变量sglNumber的声明语句放在了所有过程之外,让它成为模块级变量,这样所有过程中的语句就都可以访问这个变量了。
Option ExplicitDim sglNumber As Single '模块级变量,用于暂存第1个运算数Private Sub Command13_Click() '单击加法按钮sglNumber = Text1.Text '保存第1个运算数Text1.Text = "" '用空串赋值,即可清空文本框End SubPrivate Sub Command12_Click() '单击等号按钮Text1.Text = sglNumber + Val(Text1.Text) '做加法运算并输出End SubRem 以下省略了所有数字按钮和小数点按钮的单击事件过程代码(2)通用运算代码要能够进行四则运算,在单击等号按钮时,程序必须知道用户单击的是哪一个运算符,才能选用相应的计算公式。
因此必须在用户单击运算符按钮时记下按钮的标记,到后续计算时才能够作出正确的选择。
保存按钮标记的变量必须是模块级变量。
Option ExplicitDim sglNumber As Single '模块级变量,用于暂存第1个运算数Dim strOperator As String '模块级变量,用于保存运算符标记Private Sub Command13_Click() '单击加法按钮sglNumber = Text1.Text '保存第1个运算数strOperator = Command13.Caption '保存运算符标记Text1.Text = ""End SubPrivate Sub Command14_Click() '单击减法按钮sglNumber = Text1.Text '保存第1个运算数strOperator = Command14.Caption '保存运算符标记Text1.Text = "" '清空文本框End SubPrivate Sub Command15_Click() '单击乘法按钮sglNumber = Text1.Text '保存第1个运算数strOperator = Command15.Caption '保存运算符标记Text1.Text = "" '清空文本框End SubPrivate Sub Command16_Click() '单击除法按钮sglNumber = Text1.Text '保存第1个运算数strOperator = Command16.Caption '保存运算符标记Text1.Text = "" '清空文本框End SubPrivate Sub Command12_Click() '单击等号按钮If strOperator = "+" Then Text1.Text = sglNumber + Val(Text1.Text) '加法If strOperator = "-" Then Text1.Text = sglNumber - Val(Text1.Text) '减法If strOperator = "*" Then Text1.Text = sglNumber * Val(Text1.Text) '乘法If strOperator = "/" Then Text1.Text = sglNumber / Val(Text1.Text)'除法Text1.SetFocusText1.SelStart = 0Text1.SelLength = Len(Text1.Text)End SubRem 以下省略了所有数字按钮和小数点按钮的单击事件过程代码5. 多路选择语句程序设计语言都提供了一种多路选择处理结构,或者称多路分支结构语句,在VB中多路选择语句叫Select Case语句,它的语法格式如下:Select Case <匹配条件表达式>Case <情形1><语句块1>[Case <情形2><语句块2>……[Case <情形n><语句块n>][Case Else<语句块n+1>]]End Select图3-7 多路选择语句流程这是一种1个入口多个出口的结构(见图3-7),哪个条件匹配,就从哪个出口通行。