C语言程序设计(双语)课件2.4_Data_types

  • 格式:pps
  • 大小:163.50 KB
  • 文档页数:37

Solutions for Chapter 1Review Question SolutionNo.10A source file contains the actual text of a program and is designedto be edited by people.An object file is created by the compiler and contains a machine-language representation of the program.Most programmers never work directly with object files.No.12False,Even the best programmers make mistakesNo.13False. Between 80 and 90 percent of the cost of a program comes from maintaining that program after it is putinto practice.Solution to Programming ExercisesP.55No.4/** File: interest.c* ----------------* This program calculates simple interest for one year.*/#include <stdio.h>main(){double balance, rate, interest;printf("Interest calculation program.\n");printf("Starting balance? ");scanf("%lf",&balance);printf("Annual interest rate percentage? ");scanf("%lf",&rate);interest = balance * rate / 100;balance = balance + interest;printf("Balance after one year: %g\n", balance);}Solution to Programming Exercises /*P.55No.5* File: int2yr.c* --------------* This program calculates compound interest over two years.*/#include <stdio.h>main(){double balance, rate, interest;printf("Interest calculation program.\n");printf("Starting balance? ");scanf("%lf",&balance);printf("Annual interest rate percentage? ");scanf("%lf",&rate);interest = balance * rate / 100;balance = balance + interest;printf("Balance after one year: %g\n", balance);interest = balance * rate / 100;balance = balance + interest;printf("Balance after two years: %g\n", balance);}2.4 Data typesRelated Chapters Sections :1.Roberts,2.4~2.5 P.33~P.512.Tan Haoqiang,Chapter 3 p.41~p.61ObjectivesTo recognize the existence of different data types,including int,float, character,and string. To be able to specify simple computation through the use of arithmetic expressions; To understand the process of numeric conversion;To be able to write new programs by modifications to existing programs.Data-TypesIntegers Floating Point Charactershort float charint doublelong long double•See TAN Chapter 3 p.43 for a complete list of the Integer data-types.•See TAN Chapter 3 p.46 for a complete list of the Floating Point data-types.•See Roberts P.652 Appendix for a complete list of Special character•Character strings in C are implemented as arrays. See TAN Chapter 7 p. 130.Floating-point constants2.99792.9979*108 can be written in C as2.9979E+8The E stands for the words times 10 to the power.Variable namesSee Roberts:p.39Variable Names -reference to memory locations storing data values. A variable name is one example of an identifier in C.Variable name rules:⏹An identifier can use a combination of letters, numerical digits, and the underscore ( _ ) that starts with a letter.⏹Identifiers cannot be the same as a reserved word or keyword, such as void, float, or return. (P.39 list all of the reserved words)Use descriptive variable names.Examples: x sum force2 rate_Of_ChangeExamples of invalid variable names (why?):2force rate-of-change x.5 return⏹C case-sensitive, so that the following three names all represent different variables (i.e., different storage locations):time Time TIME#include <stdio.h> void main(void){int ssn;printf(”Please enter your SSN (no dashes):”);scanf(”%d”,&ssn); printf(”Hello %d !\n”,ssn); }The printf and scanf functions appear in …expression‟ statements.1st executablestatement3rd executablestatement 2nd executablestatementExecutable StatementsExecutable Statements Statements are grouped by their type:•assignment statement•expression statement•do-while and while statements•for statement•if and if-else statements•return statement•switch statementEvery executable statement in C must be followed by a “ ;“ semicolon.Assignment Statementsvariable= expression;•Interpretation: compute the value on theright-hand-side of the = and put this value in memory at location named (or tagged) by the name variable.•an expression can be a constant, a variable or operators with operands.Constants•Literal Constants(examples)Numeric: 3 6.248 -7.25 1.5e4(=15000)Single Character:'A' 'a' '9' '+' ' 'Character String:“Enter a positive number: ”•Symbolic Constants(example)#define PI 3.14159265/* preprocessor directive */Standard practice is to use all upper-case letters for the constant name, to avoid confusion with a variable name.A “constant” means you cannot change the value, e.g.PI = 3.0;will generate a compiler error.•for integer arithmetic, the / operator yields an integer result, and %gives the remainder after dividing twointegers. E.g.,5 / 31 5 / 605 % 32 5 % 6 5(Note: division by 0 creates an "overflow" run-timeerror.)•use arithmetic operators, with parentheses for grouping; e.g.,(a -b) / (2 * c)e.g, without parentheses, the example above would evaluate b/2first, then do the multiplication, then thesubtraction.+Addition -Subtraction *Multiplication /Division %modulus (no ^ operator in C)Arithmetic Operators( )Higher *, /, %(left to right for tie)+,-(left to right for tie)Lower(see Appendix A p. 653 for a complete list of operators and their precedence)Examples,: x = 3 + 2 * 3;/* x now has the value 9 */y = 3 * 2 % 3;/* y now has the value 0 */-Precedence Order for Arithmetic Operators:Rules of PrecedenceQuiz:what’s the result of this arithmetic expression?8*(7-6+5)%(4+3/2)-1The result is 2Exercises:Suppose there is a number of three digits,and denoted as the a,b,and c.Now you need to convert the sequence abc to the bac,can you write the expression of it?e.g. 123 to 213假设m是一个三位数,从左到右用a,b,c表示各位的数字,则从左到右各个数字是bac 的三位数的表达式是什么?m/10%10*100+m/100*10+m%10Type conversionThe integer 1 is converted internally into the floating-pointer number 1.0 before the addition is performed.1+2.3Type Cast•The unary operator that consists of the desired type in parenthesisfollowed by the value you wish toconvert.int num,den;float quotient;quotient=num/(double)den;+,-, *, /x op y ;where op is If x and y have different (mixed) data types then C automatically converts data from the lower rank to the higher rank and then performs the computation. Note: %(modulus) is only defined on integers.The ranking is given by the following table.Conversion of values with mixed data types in an expression using arithmetic operatorslong double Higherdoublefloatlong integerintegershort integer LowerType ConversionType ConversionFor Example:int i,e;float f;double d;10 + 'a' + i*f -d/eWhat’s the type of expression result?•Exampleint time;...time = 0;.Main MemoryMemory map after the assignment statement time = 0is executedtime1200.Memory map before the assignment statement time = 0is executedMain Memorytime unknown1200•Exampledouble force;force = 5.0;...force = force * 3.0;.1400Memory map after the assignment statementforce = force * 3.0; is executed15.0forceMain Memory.1400Memory map before the assignment statementforce = force * 3.0;but after force = 5.0;is executed5.0forceMain MemoryCharacter ValuesIndividual characters may be assign to variables of data-type char. Example: Write a program to prompt the user for a Y/ N response.Print the users response to the screen.#include <stdio.h>void main(void){char letter;printf(“Please enter a response (Y/N):”);scanf(“%c”,&letter);printf(“Your response was: %c \n”,letter);}Expression Statement One form of a expression statement in C : function(argument list);accepts input from standard input device,usually a keyboardscanf("format string", &var1, &var2, ...);where “format string”is the string of conversion specifies for the various data types in the variable list. e.g.,%i,%d-decimal integer (d=decimal)%f-float%lf-double(where lf="long float")%Lf-long double%c-characterThe number of conversion specifies should match the number of variables that follow the “format string”.sends output to standard output device,usually a video monitorprintf("format string", output-list);where ”format string” can contain characters to be output and the conversion specifies indicating type and position of the output values. For output, we specify formats conversion specifies) a little differently than we do for input. For example:%i, %d -decimal integer%o-octal integer%x, %X -hex integer (use X for caps A -F)%f -float, double%c -character%s -character stringOutput control:Special characters Each is represented by an escape sequence,which is a backslash (\)and an escape character. Examples are:\" -output double quotes\b –backspace\? -output question-markcharacter (?)\\-output backslashcharacter (\)\n -new lineOutput Control:Field WidthThe number of print positions to be used in the output of display values. For floating-point numbers, we can also specify the number of digits to be displayed after the decimal point.Examples:%3d-display an integer using 3 print positions.%7.3f-display a floating-point number (float, or double) using a total field width of 7 and with 3 places after the decimal point.printf and scanf examplesExample:scanf("%i %f %lf %c", &n, &a, &x, &code);Example:printf("The sum of %i values is %f.\n“,numValues, sum);printf("%s\n", "Temperature Variations");printf("The output is: \n");Examples p.47 ave2f.c/** File: ave2f.c* -------------* This program reads in two floating-point numbers and* computes their average.*/#include <stdio.h>main(){double n1, n2, average;printf("This program averages two floating-point numbers.\n"); printf("1st number? ");scanf(“%lf”,&n1);printf("2nd number? ");scanf(“%lf”,&n2);average = (n1 + n2) / 2;printf("The average is %g\n", average);}Examples P.36 greeting.cExamples/** File: cmtofeet.c* ----------------* This program reads in a length given in centimeters and converts * it to its English equivalent in feet and inches.*/#include <stdio.h>main(){double totalInches, cm, inch;int feet;printf("This program converts centimeters to feet and inches.\n");printf("Length in centimeters? ");scanf("%lf",&cm);totalInches = cm / 2.54;feet = totalInches / 12;inch = totalInches -feet * 12;printf("%g cm = %d ft %g in\n", cm, feet, inch);}What have I learned in this lecture?To accept input typed by the user,you use thefunction scanf() from the stdio libraryTo display the messages and data values onthe computer screen,you use the functionprintf() from the stdio library.Constants,variables,and arithmetic expression.The precedence of mathematic operatorsAutomatic conversion between numeric typesand explicit conversion between numerictypes.QUIZ:What is the value of the following C expression? What is its type?10 * (9 + (8 * 7 -(6 + 5) % 4 * 3) * 2) + 1Quiz 2:The following C program is compiled and runs successfully.Write the output that this program produces.#include <stdio.h>main( ){int a;float b;a = 7.0/3.0;printf(“%d \n”, a);a = 9 % 4;printf(“%d \n”, a);b = 4 + 6.0 / 2;printf(“%.1f \n”, b);}AssignmentsTo reverse the sequence of a three-digit number e.g:123 321P.54 No.19,22P.55 No.6,7。