vel07.htm

来自「简单的说明如何使用VB,非常适合初学使用者,而且是用图表来解说的」· HTM 代码 · 共 2,743 行 · 第 1/4 页

HTM
2,743
字号
><FONT COLOR=#000080>Adjust ^ 3</FONT><TD VALIGN=top  BGCOLOR=#80FFFF ><FONT COLOR=#000080>Raises a value to a power</FONT><TR><TD VALIGN=top  BGCOLOR=#80FFFF ><FONT COLOR=#000080>&amp; or +</FONT><TD VALIGN=top  BGCOLOR=#80FFFF ><FONT COLOR=#000080>Name1 &amp; Name2</FONT><TD VALIGN=top  BGCOLOR=#80FFFF ><FONT COLOR=#000080>Concatenates two strings</FONT></TABLE><P>Suppose that you wanted to store the difference between the annual sales (stored in a variable named AnnualSales) and cost of sales (stored in a variable named CostOfSales) in a variable named NetSales. Assuming that all three variables have been defined and initialized, the following assignment statement computes the correct value for NetSales:<BR><BR><PRE><FONT COLOR="#000080">NetSales = AnnualSales - CostOfSales</FONT></PRE><P>This assignment tells Visual Basic to compute the value of the expression and to store the result in the variable named NetSales. Of course, you can store the results of this expression in Caption or Text properties, too.<BR><P>If you want to raise a value by a power&#151;which means to multiply the value by itself a certain number of times&#151;you can do so. The following code assigns 10000 to Value because ten raised to the fourth power&#151;10x10x10x10&#151;is 10,000:<BR><PRE><FONT COLOR="#000080">Years = 4Value = 10 ^ Years</FONT></PRE><P>No matter how complex the expression is, Visual Basic computes the entire result before it stores that result in the variable at the left of the equals sign. The following assignment statement, for example, is rather lengthy, but Visual Basic computes the result and stores the value in the variable named Ans:<BR><BR><PRE><FONT COLOR="#000080">Ans = 8 * Factor - Pi + 12 * MonthlyAmts</FONT></PRE><P>Combining expressions often produces unintended results because Visual Basic computes mathematical results in a predetermined order. Visual Basic always calculates exponentiation first if one or more ^ operators appear in the expression. Visual Basic then computes all multiplication and division before any addition and subtraction.<BR><P>Visual Basic assigns 13 to Result in the following assignment:<BR><BR><PRE><FONT COLOR="#000080">Result = 3 + 5 * 2</FONT></PRE><P>At first, you might think that Visual Basic would assign 16 to Result because 3 + 5 is 8 and 8 * 2 is 16. However, the rules state that Visual Basic always computes multiplication&#151;and division if division exists in the expression&#151;before addition. Therefore, Visual Basic first computes the value of 5 * 2, or 10, and next adds 3 to 10 to get 13. Only then does it assign the 13 to Result.<BR><P>If both multiplication and division appear in the same expression, Visual Basic calculates the intermediate results from left to right. For example, Visual Basic assigns 20 to the following expression:<BR><BR><PRE><FONT COLOR="#000080">Result = 8 / 2 + 4 + 3 * 4</FONT></PRE><P>Figure 7.1 shows how Visual Basic computes this expression. Visual Basic computes the division first because the division appears to the left of the multiplication. If the multiplication appeared to the left of the division, Visual Basic would have multiplied first. After Visual Basic calculates the intermediate answers for the division and the multiplication, it performs the addition and stores the final answer of 20 in Result.<BR><P><B> <A HREF="07vel01.gif">Figure 7.1. Visual Basic computes expressions in </B><B>a predetermined order.</A></B><BR><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Note: </B>The order of computation has many names. Programmers usually use one of these terms: o<I>rder of </I><I>operators</I>, <I>operator precedence</I>, or <I>math hierarchy</I>.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><P>It is possible to override the operator precedence by using parentheses. Visual Basic always computes the values inside any pair of parentheses before anything else in the expression, even if it means ignoring operator precedence. The following assignment statement stores 16 in Result because the parentheses force Visual Basic to compute the addition before the multiplication:<BR><BR><PRE><FONT COLOR="#000080">Result = (3 + 5) * 2</FONT></PRE><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Tip: </B><A HREF="velxb.htm">Appendix B</A> contains the complete Visual Basic operator precedence table. The table contains several operators that you have yet to learn about, so you might not understand the full table at this time.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><P>The following expression stores the fifth root of 125 in the variable named root5:<BR><BR><PRE><FONT COLOR="#000080">root5 = 125 ^ (1/5)</FONT></PRE><P>As you can see from this expression, Visual Basic supports fractional exponents.<BR><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><I>Definition: Concatenation</I> means the joining together of two or more strings.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><P>One of Visual Basic's primary operators has nothing to do with math. The concatenation operator joins one string to the end of another. Suppose that the user entered his first name in a label control named lblFirst and his last name in a label control named lblLast. The following concatenation expression stores the full name in the string variable named FullName:<BR><BR><PRE><FONT COLOR="#000080">FullName = lblFirst &amp; lblLast</FONT></PRE><P>There is a problem here, though, that might not be readily apparent&#151;there is no space between the two names. The &amp; operator does not automatically insert a space because you don&#146;t always want spaces inserted when you concatenate two strings. Therefore, you might have to concatenate a third string between the other two, as in<BR><BR><PRE><FONT COLOR="#000080">FullName = lblFirst &amp; &quot; &quot; &amp; lblLast</FONT></PRE><P>Visual Basic actually supports a synonym operator, the plus sign, for concatenation. In other words, the following assignment statement is identical to the previous one:<BR><BR><PRE><FONT COLOR="#000080">FullName = lblFirst + &quot; &quot; + lblLast</FONT></PRE><P>Even Microsoft, the maker of Visual Basic, recommends that you use &amp; for string concatenation and reserve + for mathematical numeric additions. Using the same operator for two different kinds of operations can lead to confusion.<BR><P><FONT COLOR="#FF8000"><B><I>Review: </I></B></FONT>The math operators enable you to perform all kinds of calculations and assignments. Visual Basic means never having to use a calculator again! When you use expressions, however, remember operator precedence. When in doubt, use parentheses to indicate exactly which operations in an expression you want Visual Basic to calculate first.<BR><BR><A NAME="E68E59"></A><H3 ALIGN=CENTER><CENTER><FONT SIZE=5 COLOR="#FF0000"><B>The </B><FONT COLOR="#FF8000"><B><I>Val()</I></B></FONT><B> Function</B></FONT></CENTER></H3><BR><P><FONT COLOR="#FF8000"><B><I>Concept: </I></B></FONT>Visual Basic treats all data stored in controls on the form as variant values. There is a quirk in Visual Basic that makes Visual Basic think these controls are strings when you want to add two control values together. The Val() function makes sure that Visual Basic treats control values as numbers when you need numbers for expressions.<BR><P>Figure 7.2 shows a simple form with two text boxes and a command button. As soon as the user types last year's sales into a text box named txtLast and this year's sales into a text box named txtThis, the command button triggers a Click event procedure that does the following:<BR><BR><PRE><FONT COLOR="#000080">lblAvg = (txtLast.Text + txtThis.Text) / 2</FONT></PRE><P><B> <A HREF="07vel02.gif">Figure 7.2. Computes the average sales value for </B><B>two years.</A></B><BR><P>Despite the fact that everything is correct about this expression, Visual Basic does not store the average of the two text boxes in the lblAvg label. Visual Basic incorrectly thinks that you want to concatenate the two text box values instead of adding them.<BR><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Note: </B>See the problems that can occur when a language uses the same operator, +, for two different purposes!</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><P>Instead of using this relatively simple expression, you must add a little mess by using the Val() function. The word Val() looks like the name of an event procedure because of the parentheses. However, Visual Basic has several built-in routines called <I>functions. </I>Function names end with parentheses. You will learn all about Visual Basic functions in Lesson 7. For now, just use the functions&#151;they're easy&#151;and don&#146;t worry about how they work.<BR><P>Here's how you use Val(): Put a string&#151;or something that Visual Basic might think is a string, such as a control&#151;inside the parentheses. As long as the parenthetical value can be interpreted as a number, even if the value is stored as a string, Visual Basic converts the value to a number temporarily so that you can calculate a mathematical result. The previous assignment requires that you use Val() twice. For example, instead of<BR><BR><PRE><FONT COLOR="#000080">lblAvg = (txtLast.Text + txtThis.Text) / 2</FONT></PRE><P>you must code<BR><BR><PRE><FONT COLOR="#000080">lblAvg = (Val(txtLast.Text) + Val(txtThis.Text)) / 2</FONT></PRE><P>Val() ensures that Visual Basic treats the text boxes as numeric quantities and not as strings.<BR><P>By the way, if the user does not enter numbers in both text boxes, Visual Basic uses zero for the converted number if no numeric digits appear in the text boxes. If any number or set of digits appears in the text boxes, Val() uses those digits for the converted number, often producing funny results. For example, if txtLast.Text contains 18 years old (why the user would type <I>that</I> for a sales figure is beyond me!), Val() strips off the 18 and uses 18 for the numeric value in the average calculation.<BR><BLOCKQUOTE><BLOCKQUOTE><HR ALIGN=CENTER><BR><NOTE><B>Note: </B>You can find this simple sales averaging program under the name SALAVG.MAK on the disk that comes with this book. The program is extremely simple. It does not format the average to dollars and cents, so you might have more or fewer than two decimal places. Nevertheless, you can load and study the program's cmdAvg_Click() procedure to get a feel for the calculation being performed and for how Val() helps the calculation.</NOTE><BR><HR ALIGN=CENTER></BLOCKQUOTE></BLOCKQUOTE><P><FONT COLOR="#FF8000"><B><I>Review: </I></B></FONT>When you calculate using the form's data, you might have to convert control values to numbers temporarily by using Val() before you use the values in numeric expressions. The controls retain their variant data types except for the locations where Val() converts the label data types to numbers.<BR><BR><A NAME="E68E60"></A><H3 ALIGN=CENTER><CENTER><FONT SIZE=5 COLOR="#FF0000"><B>Homework</B></FONT></CENTER></H3><BR><BR><A NAME="E69E51"></A><H4 ALIGN=CENTER><CENTER><FONT SIZE=4 COLOR="#FF0000"><B>General Knowledge</B></FONT></CENTER></H4><BR><OL><LI>What is a variable?<BR><BR><LI>What statement defines variables?<BR><BR><LI>What is a data type?<BR><BR><LI>Name the seven Visual Basic data types.<BR><BR><LI>Which data type holds the smallest range of values?<BR><BR><LI>Which data type holds the largest range of values?<BR><BR><LI>Which data types always have decimal places?<BR><BR><LI>What does the E mean when it appears inside numbers?<BR><BR><LI>What does scientific notation do?<BR><BR><LI>True or false: Constants can change throughout a program.<BR><BR><LI>True or false: Variables can stay the same throughout a program.<BR><BR><LI>Why is it helpful to define all variables before you use them?<BR><BR><LI>What is the difference between a variable-length string and a fixed-length string?<BR><BR><LI>True or false: You can store control property values in variables.<BR><BR><LI>True or false: You can store variables in control property values.<BR><BR><LI>Given the Visual Basic order of precedence, what value is assigned to the left-hand variables in each of the following assignment statements?<BR><BR><OL TYPE=A><LI>ResultA = 1 + 2 * 3<BR><BR><LI>ResultB = (1 + 2) * 3<BR><BR><LI>ResultC = 2 ^ 4<BR><BR><LI>Average = 10 + 20 + 30 / 3<BR><BR><LI>Num = 10 - 3 * 2 + 4 / 2<BR><BR><LI>Ans = 10 * 2 ^ 2</OL><BR><BR><LI>What does it mean to concatenate two strings?<BR><BR><LI>What is the difference between + and &amp;?<BR><BR></OL><BR><A NAME="E69E52"></A><H4 ALIGN=CENTER><CENTER><FONT SIZE=4 COLOR="#FF0000"><B>Write Code That...</B></FONT></CENTER></H4><BR><OL><LI>Define a variable that holds the exact square footage measurement of your home. Use a variable that can accept a decimal point, but don't exaggerate and define a variable that is much larger than you really need.<BR><BR><LI>Rewrite the following assignment statements so that they are shorter:<BR>Let SalesPrice = Price / Discount<BR>Let Tax = TaxRate * SalesPrice<BR><BR></OL><BR><A NAME="E69E53"></A><H4 ALIGN=CENTER><CENTER><FONT SIZE=4 COLOR="#FF0000"><B>Find the Bug</B></FONT></CENTER></H4><BR><OL><LI>What is wrong with the following variable definition?<BR>Dim MyAge As Integer<BR>Dim Height As Single<BR>Dim Weight As Double<BR>Dim Name As String<BR><BR><LI>Judy is having problems with her Visual Basic program. She declared three variables that she wants to use for three totals:<BR>Dim DivTotal As Single<BR>Dim DivTotal As Single<BR>Dim DivTotal As Single<BR>Judy's goal is to store the inventory totals for each of her company's divisions in the three variables. Visual Basic does not like what she is doing. Help Judy out because her boss is getting snippy.<BR><BR><LI>Larry Derryberry gets an error when he assigns the following currency variable the value. Tell Larry what he is doing wrong.<BR>Salary = $47,533.90<BR><BR></OL><BR><A NAME="E69E54"></A><H4 ALIGN=CENTER><CENTER><FONT SIZE=4 COLOR="#FF0000"><B>Extra Credit</B></FONT></CENTER></H4><BR><P>Add a third label to the SALAVG.MAK averaging program shown in Figure 7.2 so that the program averages three sales values.<BR><P ALIGN=LEFT><A HREF="velp03.htm" TARGET="_self"><IMG SRC="purprev.gif" WIDTH = 32 HEIGHT = 32 BORDER = 0 ALT="Previous Page"></A><A HREF="#I0" TARGET="_self"><IMG SRC="purtop.gif" WIDTH = 32 HEIGHT = 32 BORDER = 0 ALT="Page Top"></A><A HREF="index.htm" TARGET="_self"><IMG SRC="purtoc.gif" WIDTH = 32 HEIGHT = 32 BORDER = 0 ALT="TOC"></A><A HREF="vel08.htm" TARGET="_self"><IMG SRC="purnext.gif" WIDTH = 32 HEIGHT = 32 BORDER = 0 ALT="Next Page"></A></BODY></HTML>

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?