用C++解决问题第十版-第2章C++基础_第1页
用C++解决问题第十版-第2章C++基础_第2页
用C++解决问题第十版-第2章C++基础_第3页
用C++解决问题第十版-第2章C++基础_第4页
用C++解决问题第十版-第2章C++基础_第5页
已阅读5页,还剩94页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Chapter 2C+ BasicsOverview2.1 Variables and Assignments 2.2 Input and Output2.3 Data Types and Expressions2.4 Simple Flow of Control2.5 Program StyleSlide 2- 32.1Variables and AssignmentsVariables and AssignmentsVariables are like small blackboardsWe can write a number on themWe can change the numbe

2、rWe can erase the numberC+ variables are names for memory locationsWe can write a value in themWe can change the value stored thereWe cannot erase the memory locationSome value is always thereSlide 2- 5Display 2.1IdentifiersVariables names are called identifiersChoosing variable namesUse meaningful

3、names that represent data to be storedFirst character must be a letterthe underscore characterRemaining characters must belettersnumbersunderscore characterSlide 2- 6KeywordsKeywords (also called reserved words)Are used by the C+ language Must be used as they are defined in the programming languageC

4、annot be used as identifiersSlide 2- 7Declaring Variables (Part 1) Before use, variables must be declaredTells the compiler the type of data to storeExamples: int numberOfBars; double one_weight, totalWeight;int is an abbreviation for integer.could store 3, 102, 3211, -456, etc. number_of_bars is of

5、 type integer double represents numbers with a fractional componentcould store 1.34, 4.0, -345.6, etc. one_weight and totalWeight are both of type doubleDeclaring Variables (Part 2)Immediately prior to use int main() int sum; sum = score1 + score 2; return 0;Slide 2- 9At the beginning int main() int

6、 sum; sum = score1 + score2; return 0; Two locations for variable declarationsDeclaring Variables (Part 3)Declaration syntax:Type_name Variable_1 , Variable_2, . . . ;Declaration Examples:double average, m_score, totalScore;double moonDistance;int age, numStudents;int carsWaiting;Slide 2- 10Assignme

7、nt StatementsAn assignment statement changes the value of a variabletotalWeight = oneWeight + numberOfBars; totalWeight is set to the sum oneWeight + numberOfBars Assignment statements end with a semi-colonThe single variable to be changed is always on the leftof the assignment operator = On the rig

8、ht of the assignment operator can beConstants - age = 21;Variables - myCost = yourCost;Expressions - circumference = diameter * 3.14159;Slide 2- 11Assignment Statements and AlgebraThe = operator in C+ is not an equal signThe following statement cannot be true in algebranumberOfBars = numberOfBars +

9、3;In C+ it means the new value of numberOfBars is the previous value of numberOfBars plus 3Slide 2- 12Initializing VariablesDeclaring a variable does not give it a valueGiving a variable its first value is initializing the variableVariables are initialized in assignment statementsdouble mpg; / decla

10、re the variable mpg = 26.3; / initialize the variableDeclaration and initialization can be combinedusing two methodsMethod 1double mpg = 26.3, area = 0.0 , volume;Method 2 double mpg(26.3), area(0.0), volume;Slide 2- 13Section 2.1 ConclusionCan youDeclare and initialize two integers variables to zer

11、o? The variables are named feet and inches.Declare and initialize two variables, one int and one double?Both should be initialized to the appropriate form of 5.Give good variable names for identifiers to storethe speed of an automobile?an hourly pay rate?the highest score on an exam?Slide 2- 142.2In

12、put and OutputInput and OutputA data stream is a sequence of dataTypically in the form of characters or numbersAn input stream is data for the program to useTypically originatesat the keyboardat a fileAn output stream is the programs outputDestination is typically the monitora fileSlide 2- 16Output

13、using coutcout is an output stream sending data to the monitorThe insertion operator inserts data into coutExample: cout numberOfBars candy barsn;This line sends two items to the monitorThe value of numberOfBarsThe quoted string of characters candy barsnNotice the space before the c in candyThe n ca

14、uses a new line to be started following the s in barsA new insertion operator is used for each item of outputSlide 2- 17Examples Using coutThis produces the same result as the previous sample cout numberOfBars; cout candy barsn;Here arithmetic is performed in the cout statement cout Total cost is $

15、(price + tax);Quoted strings are enclosed in double quotes (Walter)Dont use two single quotes ()A blank space can also be inserted with cout ;if there are no strings in which a space is desired as in candy barsn Slide 2- 18Include Directives Include Directives add library files to our programsTo mak

16、e the definitions of the cin and cout available to the program: #include Using Directives include a collection of defined namesTo make the names cin and cout available to our program: using namespace std;Slide 2- 19Escape SequencesEscape sequences tell the compiler to treat characters in a special w

17、ay is the escape characterTo create a newline in output use n cout n; or the newer alternative cout endl;Other escape sequences: t - a tab - a backslash character - a quote characterSlide 2- 20Formatting Real NumbersReal numbers (type double) produce a variety of outputsdouble price = 78.5;cout The

18、price is $ price endl; The output could be any of these: The price is $78.5 The price is $78.500000The price is $7.850000e01The most unlikely output is: The price is $78.50Slide 2- 21Showing Decimal Placescout includes tools to specify the output of type doubleTo specify fixed point notationsetf(ios

19、:fixed) To specify that the decimal point will always be shown setf(ios:showpoint)To specify that two decimal places will always be shown precision(2)Example:cout.setf(ios:fixed);cout.setf(ios:showpoint);cout.precision(2);cout The price is price ) removes data to be usedExample:cout Enter the number

20、 of bars in a packagen; cout numberOfBars; cin oneWeight;This code prompts the user to enter data thenreads two data items from cinThe first value read is stored in numberOfBarsThe second value read is stored in oneWeightData is separated by spaces when enteredSlide 2- 23Reading Data From cinMultipl

21、e data items are separated by spacesData is not read until the enter key is pressedAllows user to make correctionsExample: cin v1 v2 v3;Requires three space separated values User might type 34 45 12 Slide 2- 24Designing Input and OutputPrompt the user for input that is desiredcout statements provide

22、 instructions cout age;Notice the absence of a new line before using cinEcho the input by displaying what was readGives the user a chance to verify datacout age was entered. symbol1 symbol2;User normally separate data items by spaces J DResults are the same if the data is not separated by spaces JDS

23、lide 2- 37Display 2.4Type stringstring is a class, different from the primitive data types discussed so farDifference is discussed in Chapter 8Use double quotes around the text to store into the string variableRequires the following be added to the top of your program:#include To declare a variable

24、of type string: string name = Apu Nahasapeemapetilon;Slide 2- 38Display 2.5Type CompatibilitiesIn general store values in variables of the same typeThis is a type mismatch: int intVariable; intVariable = 2.99;If your compiler allows this, intVariable willmost likely contain the value 2, not 2.99Slid

25、e 2- 39int double (part 1)Variables of type double should not be assignedto variables of type int int intVariable; double doubleVariable; doubleVariable = 2.00; intVariable = doubleVariable;If allowed, intVariable contains 2, not 2.00Slide 2- 40int double (part 2)Integer values can normally be store

26、d in variables of type double double doubleVariable; doubleVariable = 2;doubleVariable will contain 2.0Slide 2- 41char intThe following actions are possible but generally not recommended!It is possible to store char values in integervariables int value = A;value will contain an integer representing

27、AIt is possible to store int values in charvariables char letter = 65;Slide 2- 42bool intThe following actions are possible but generally not recommended!Values of type bool can be assigned to int variablesTrue is stored as 1False is stored as 0Values of type int can be assigned to boolvariablesAny

28、non-zero integer is stored as trueZero is stored as falseSlide 2- 43ArithmeticArithmetic is performed with operators+ for addition- for subtraction* for multiplication/ for divisionExample: storing a product in the variable totalWeight totalWeight = oneWeight * numberOfBars;Slide 2- 44Results of Ope

29、ratorsArithmetic operators can be used with any numeric typeAn operand is a number or variable used by the operatorResult of an operator depends on the types of operandsIf both operands are int, the result is intIf one or both operands are double, the result is doubleSlide 2- 45Division of DoublesDi

30、vision with at least one operator of type doubleproduces the expected results. double divisor, dividend, quotient; divisor = 3; dividend = 5; quotient = dividend / divisor;quotient = 1.6666 Result is the same if either dividend or divisor is of type intSlide 2- 46Division of IntegersBe careful with

31、the division operator!int / int produces an integer result (true for variables or numeric constants) int dividend, divisor, quotient; dividend = 5; divisor = 3; quotient = dividend / divisor; The value of quotient is 1, not 1.666Integer division does not round the result, the fractional part is disc

32、arded!Slide 2- 47Integer Remainders% operator gives the remainder from integer division int dividend, divisor, remainder; dividend = 5; divisor = 3; remainder = dividend % divisor; The value of remainder is 2Slide 2- 48Display 2.6Arithmetic ExpressionsUse spacing to make expressions readableWhich is

33、 easier to read? x+y*z or x + y * z Precedence rules for operators are the same as used in your algebra classesUse parentheses to alter the order of operations x + y * z ( y is multiplied by z first) (x + y) * z ( x and y are added first)Slide 2- 49Display 2.7Operator ShorthandSome expressions occur

34、 so often that C+ contains to shorthand operators for themAll arithmetic operators can be used this way+= count = count + 2; becomes count += 2;*= bonus = bonus * 2; becomes bonus *= 2;/= time = time / rushFactor; becomes time /= rushFactor;%= remainder = remainder % (cnt1+ cnt2); becomes remainder

35、%= (cnt1 + cnt2);Slide 2- 502.4Simple Flow of ControlSimple Flow of ControlFlow of controlThe order in which statements are executedBranchLets program choose between two alternativesSlide 2- 52Branch ExampleTo calculate hourly wages there are two choicesRegular time ( up to 40 hours)grossPay = rate

36、* hours;Overtime ( over 40 hours)grossPay = rate * 40 + 1.5 * rate * (hours - 40);The program must choose which of these expressions to useSlide 2- 53Designing the BranchDecide if (hours 40) is trueIf it is true, then use grossPay = rate * 40 + 1.5 * rate * (hours - 40);If it is not true, then use g

37、rossPay = rate * hours;Slide 2- 54Implementing the Branchif-else statement is used in C+ to perform a branchif (hours 40)grossPay = rate * 40 + 1.5 * rate * (hours - 40);else grossPay = rate * hours;Slide 2- 55Display 2.8Display 2.9Boolean ExpressionsBoolean expressions are expressions that are eith

38、er true or falsecomparison operators such as (greater than) are used to compare variables and/or numbers(hours 40) Including the parentheses, is the boolean expression from the wages exampleA few of the comparison operators that use two symbols (No spaces allowed between the symbols!)= greater than

39、or equal to!= not equal or inequality= = equal or equivalentSlide 2- 56Display 2.10if-else Flow Control (1)if (boolean expression) true statementelse false statementWhen the boolean expression is trueOnly the true statement is executedWhen the boolean expression is falseOnly the false statement is e

40、xecutedSlide 2- 57if-else Flow Control (2)if (boolean expression) true statements else false statements When the boolean expression is trueOnly the true statements enclosed in are executedWhen the boolean expression is falseOnly the false statements enclosed in are executedSlide 2- 58AND Boolean exp

41、ressions can be combined intomore complex expressions with& - The AND operatorTrue if both expressions are trueSyntax: (Comparison_1) & (Comparison_2)Example: if ( (2 x) & (x 7) )True only if x is between 2 and 7Inside parentheses are optional but enhance meaningSlide 2- 59OR| | - The OR operator (n

42、o space!)True if either or both expressions are trueSyntax: (Comparison_1) | | (Comparison_2)Example: if ( ( x = = 1) | | ( x = = y) )True if x contains 1True if x contains the same value as yTrue if both comparisons are trueSlide 2- 60NOT! - negates any boolean expression!( x y)True if x is NOT les

43、s than y!(x = = y)True if x is NOT equal to y! Operator can make expressions difficult to understanduse only when appropriateSlide 2- 61InequalitiesBe careful translating inequalities to C+if x y z translates as if ( ( x y ) & ( y z ) ) NOT if ( x y 0) cout Hello ; countDown -= 1; Output: Hello Hell

44、o Hello when countDown starts at 3Slide 2- 66Display 2.12While Loop OperationFirst, the boolean expression is evaluatedIf false, the program skips to the line following the while loopIf true, the body of the loop is executedDuring execution, some item from the boolean expressionis changedAfter execu

45、ting the loop body, the boolean expression is checked again repeating the processuntil the expression becomes falseA while loop might not execute at all if the boolean expression is false on the first checkSlide 2- 67while Loop Syntaxwhile (boolean expression is true) statements to repeat Semi-colon

46、s are used only to end the statementswithin the loopwhile (boolean expression is true) statement to repeatSlide 2- 68Display 2.13do-while loopA variation of the while loop.A do-while loop is always executed at least onceThe body of the loop is first executedThe boolean expression is checked after th

47、e bodyhas been executedSyntax: do statements to repeat while (boolean_expression);Slide 2- 69Display 2.14Display 2.15Increment/DecrementUnary operators require only one operand+ in front of a number such as +5- in front of a number such as -5+ increment operatorAdds 1 to the value of a variable x +;

48、 is equivalent to x = x + 1;- decrement operatorSubtracts 1 from the value of a variable x -;is equivalent to x = x 1;Slide 2- 70Sample ProgramBank charge card balance of $502% per month interestHow many months without payments beforeyour balance exceeds $100After 1 month: $50 + 2% of $50 = $51After

49、 2 months: $51 + 2% of $51 = $52.02After 3 months: $52.02 + 2% of $52.02 Slide 2- 71Display 2.16Infinite LoopsLoops that never stop are infinite loopsThe loop body should contain a line that willeventually cause the boolean expression to become falseExample: Print the odd numbers less than 12 x = 1;

50、 while (x != 12) cout x endl; x = x + 2; Better to use this comparison: while ( x 0) cout x endl; x = x 3; Show the output of the previous code using the comparison x 0? Slide 2- 732.5Program StyleProgram StyleA program written with attention to style is easier to read easier to correct easier to ch

51、angeSlide 2- 75Program Style - IndentingItems considered a group should look like agroupSkip lines between logical groups of statementsIndent statements within statements if (x = = 0) statement; Braces create groupsIndent within braces to make the group clearBraces placed on separate lines are easier to locateSlide 2- 76Program Style - Comments/ is the symbol for a single line commentComments are explanat

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论