中国高校课件下载中心 》 教学资源 》 大学文库

英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 4 - Simple Data Types

文档信息
资源类别:文库
文档格式:PDF
文档页数:4
文件大小:27.04KB
团购合买:点击进入团购
内容简介
英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 4 - Simple Data Types
刷新页面文档预览

rodaioBraryRepresertaloLecture 4MachineCodeAs wehave seen,programs exist as binarymachinecode.Thisisinconvenientforhumansas we can not naturally interpret the code.8Laopin9Ann:Toovercomethis,assemblylanguagewasn10Bosinvented, e.g.LDA 1Bc9aamortomass11SingADD05 ad ip acumulatrSTA1AF7soeerts 1AF7:This is translatedmore or less directly intomachinecodebyaprogramcalledanSmassemblercoraloCrnmAssemblerCompilersnExecutablefileProganSource FileAssemblerObject FileLinkerObject(machine code) (assemibler code)(program)CampilerProyarS2Forcomplexprogramsweneedagreaterlevel:Acompileris used to convertthe HLL source codeof abstraction which is offeredby high levelinto an object file,which is then possibly combinedlanguagessuchascwith others to produce an executable program.Other object files can come from other programmers,e.g.x=newwindow(200,300,x_pos,y_pos):libraries (e.g.maths,graphics),assembler or othery=l+sin(theta)-cos(phi)/2;HLLSerEErrorsEpoouind 1,utoOTTOT.:TTn kuemiwne,iw中Several types of error can occur when developing programsROTTUTIE>notThey are allintroduced bythe programmer,not the computer!HHEEaooBATAetord3“:f1b Compiletime errors (reported by the compiler)T1eT n Fa) Syntax errors, e.g. missing semicolon at end of statementt11de0b)manicosgfrgeingtoincudsdoh>henuingi(which therefore doesn't mean anything)电真Run time errors龍the program compiles ok but crashes when it is ran, e-g, zwxly, where商0y=0OET- Algorithmic errorswhat is intended1theprogramcompilessok,butdoe:S:Bu:3

1 1. Introduction 2. Binary Representation 3. Hardware and Software 4. High Level Languages 5. Standard input and output 6. Operators, expression and statements 7. Making Decisions 8. Looping 9. Arrays 10. Basics of pointers 11. Strings 12. Basics of functions 13. More about functions 14. Files 14. Data Structures 16. Case study: lottery number generator Lecture 4 Machine Code • As we have seen, programs exist as binary machine code. This is inconvenient for humans as we can not naturally interpret the code. • To overcome this, assembly language was invented, e.g. LDA 1BC9 - load accumulator from address 1BC9 ADD 05 - add 5 to accumulator STA 1AF7 - store the result at address 1AF7 • This is translated more or less directly into machine code by a program called an assembler Assembler • For complex programs we need a greater level of abstraction which is offered by high level languages such as c e.g. x=newWindow(200,300,x_pos,y_pos); y=1+sin(theta)-cos(phi)/2; Source File Assembler Object File (assembler code) (program) (machine code) Compilers • A compiler is used to convert the HLL source code into an object file, which is then possibly combined with others to produce an executable program. • Other object files can come from other programmers, libraries (e.g. maths, graphics), assembler or other HLLs Source file Compiler Linker Executable file Object files Object file HLL Program Machine Code Machine Code Program Errors • Several types of error can occur when developing programs. They are all introduced by the programmer, not the computer! – Compile time errors (reported by the compiler) a) Syntax errors, e.g. missing semicolon at end of statement b) Semantic errors, e.g. forgetting to #include , then using printf (which therefore doesn’t mean anything) – Run time errors the program compiles ok but crashes when it is ran, e.g. z=x/y; where y=0 – Algorithmic errors the program compiles and runs ok, but doesn’t do what is intended. /* Example: anatomy of a simple C program. */ /* It's useful to put comments in your programs to explain what you're doing. Not too few, not too many: one helpful comment every 10 to 20 lines of code is probably about right. This program has far too many! */ /* Note: C doesn't allow nested comments: you can't put one comment inside another! */ #include /* This is a preprocessor directive. Most C programs need to include the standard header file , which deals with input and output. For instance, it declares the function printf, for formatted printing. */ #define ANSWER 42 /* This is another preprocessor directive. The symbol ANSWER will be replaced by 42. It's useful for defining constants. */ int a, b; /* Declared outside any function, these are external (global) variables, accessible to all functions in this file. There are good reasons for minimising the use of globals! */ int mult_and_print(float f, float g); void add(void); /* Function prototypes. Their actual definitions follow main. */ main() { /* This is a function definition. Every C program needs a main function, where execution starts. */ float x, y = 13.7; /* Declaring two local variables, visible only within the main function */ Anatomy of a Simple C Program

eroseooSimpleDatatypes inC.weeoem+itn nag0t-/e. C has only a few simple data types:/,es T的b0 1 Integer typesint, short, long- Floating point types:float, double, long doubleCharacter types. HmcharThe integer and character types can be either signeduo70:or unsigned1.NB. C does not define how many bytes each typeuses.The compiler does !!!OneandTwo'2ComplementIntegers·Consideran unsigned int variable.Suppose:Negative integers are stored in aformknown asthe compiler uses 2 bytes for this data type.oneandtwo'scomplementIt can vary from 0000 to FFFF (hex), ie. 0 to 65535 (decimal):Standard Binary number4o32o'e1No11281=9e.g.unsigned int x=65535;:One's Complement, Invertthenumberx=x+1;-1276432911m04H210= -9? Two's Complement, Invert the number and add 1.Whats thevalue ofx now?16mo41112864211.-9Iits 0000 (hex) - overflow has occurred.Two'2ComplementorlanMabudnSowhenoverflowoccurs+127+1gives??asinENBEFL337·127=OS9-12864321681-21RK01 =1271atsG5: +13P-128643216N84雪务面o00000 = 128bE名世5..1Pf0设ET+2

2 x = y * ANSWER + a; /* This is a statement */ add(); b = mult_and_print(x, y); /* These are function calls */ return; /* End of the main function */ } void add(void) /* Definition of a function */ { a = a + b; return; } int mult_and_print(float f, float g) /* Definition of a function */ { int r; /* Declaring a local variable */ r = (int) (f * g); /* A statement */ printf("Yesterday I saw %i penguins!\n", r); /* A function call; the prototype for printf is in */ return r; /* Returning a value to the calling function */ } Anatomy of a Simple C Program cont. Simple Data types in C • C has only a few simple data types: – Integer types int, short, long – Floating point types: float, double, long double – Character types char • The integer and character types can be either signed or unsigned • NB. C does not define how many bytes each type uses. The compiler does !!! Integers • Consider an unsigned int variable. Suppose the compiler uses 2 bytes for this data type. It can vary from 0000 to FFFF (hex), i.e. 0 to 65535 (decimal) e.g. unsigned int x=65535; x=x+1; • Whats the value of x now ? Its 0000 (hex) - overflow has occurred. One and Two’2 Complement • Negative integers are stored in a form known as one and two’s complement • Standard Binary number • One’s Complement, Invert the number • Two’s Complement, Invert the number and add 1 128 64 32 16 8 4 2 1 0 0 0 0 1 0 0 1 = 9 -127 64 32 16 8 4 2 1 1 1 1 1 0 1 1 0 = -9 -128 64 32 16 8 4 2 1 1 1 1 1 0 1 1 1 = -9 Two’2 Complement • So when overflow occurs +127+1 gives?? • 127= • +1 -128 64 32 16 8 4 2 1 0 1 1 1 1 1 1 1 = 127 -128 64 32 16 8 4 2 1 1 0 0 0 0 0 0 0 = -128 /* Example: demonstrates overflow of integer variables */ /* Don't worry about how the program works, just appreciate what happens! */ #include #include void main(void) { unsigned int x = UINT_MAX - 1; signed int y = INT_MAX - 1; printf("x is an unsigned int, occupying %i bytes.\n\n", sizeof(x)); printf("The initial value of x is %u\n", x); x++; printf("Add 1; the new value of x is %u\n", x); x++; printf("Add 1; the new value of x is %u\n", x); x++; printf("Add 1; the new value of x is %u\n", x); printf("\ny is a signed int, occupying %i bytes.\n\n", sizeof(y)); printf("The initial value of y is %i\n", y); y++; printf("Add 1; the new value of y is %i\n", y); y++; printf("Add 1; the new value of y is %i\n", y); y++; printf("Add 1; the new value of y is %i\n", y); return; } x is an unsigned int, occupying 4 bytes. The initial value of x is 4294967294 Add 1; the new value of x is 4294967295 Add 1; the new value of x is 0 Add 1; the new value of x is 1 y is a signed int, occupying 4 bytes. The initial value of y is 2147483646 Add 1; the new value of y is 2147483647 Add 1; the new value of y is -2147483648 Add 1; the new value of y is -2147483647 overflow.c

Sses-3E3REP-4eftton0E居Pei2管2的,nd15CEnnMS盛喜幸S8LS7RERSIEEENEPRRLEEns:122中18美墅用品1818福店4Nai24雪量品R8美1喜超1.-话通业:IntegertypesFloatingPointNumbers:Numbers like 1234.567 can be expressed in"scientific.Inthe examples weusedthe sizeofnotationas1.234567x103,or+.1234567e+4keyword to determine how many bytes aremarntssa exponentusedtostoreeachtype.We letthedecimal pointfioatto the LH end of themantissasizeof(unsigned int) or sizeof(x)Such as representation ls called fioating pointvariableWe can use a similar method to generate a binary code,data typetypically 4 bytes are used to store floating point N's·Thenames shortand long canbe The majority of bits are used for the mantissa and a few for the exponent.misleading,on inthelastexample int andBoth parts are stored as 2's complementlong were the same size.:The float type is often poor precision (6 sig figs) far worsesizeof(short)≤sizeof(int)≤sizeof (long)than a calculator C also has a doubie precision floating point type, double, which typicallyuses8bytesCharactersNamesrulesif we wish to create a new variable,sayafloating point.There is only one character type, charvariable called x, this is done byThis is defined (in ANSI C) to be a single byte.floatx: However there are restrictions on the names that wei. Depending upon the context it can be treated as ancan useinteger, so there are signed and unsigned versions Canonly include letters,digits orunderscores- char (-128 to +127)and unsigned char (0 to 255) First character cannot be a digit- Upper and lower case are distinct(ll upper used for #define).AcharvariableholdsAsCllcodesaswell assome Must not be the same as any of C's 32 keywordsescape charactersIt, do,to: b ea attot: gie. to*nnew line,"\t'tab,"La'alert(beep),"lo"nulruct,switch, typedetThe nu11 character has the code 0000000 (binary)andnice, whignea, geid, coistiie, what.has a special role in strings. Is is also sensible not to use other common C identifiers,e.g- printf3

3 sizes.c /* Example: compile and run this program to find out how your C compiler treats different data types. The result will depend on the computer and compiler you use, and possibly on the compiler settings. */ #include #include #include void main(void) { puts("With this computer and compiler, the simple C"); puts("data types have the following characteristics:\n"); puts("signed char:"); printf("\tOccupies %i byte (%i bits)\n", sizeof(signed char), CHAR_BIT); printf("\tRanges from %i to %i\n\n", CHAR_MIN, CHAR_MAX); puts("unsigned char:"); printf("\tOccupies %i bytes (%i bits)\n", sizeof(unsigned char), CHAR_BIT); printf("\tRanges from %i to %i\n\n", 0, UCHAR_MAX); puts("signed short:"); printf("\tOccupies %i bytes\n", sizeof(signed short)); printf("\tRanges from %i to %i\n\n", SHRT_MIN, SHRT_MAX); puts("unsigned short:"); printf("\tOccupies %i bytes\n", sizeof(unsigned short)); printf("\tRanges from %i to %u\n\n", 0, USHRT_MAX); puts("signed int:"); printf("\tOccupies %i bytes\n", sizeof(signed int)); printf("\tRanges from %i to %i\n\n", INT_MIN, INT_MAX); puts("unsigned int:"); printf("\tOccupies %i bytes\n", sizeof(unsigned int)); printf("\tRanges from %i to %u\n\n", 0, UINT_MAX); puts("signed long:"); printf("\tOccupies %i bytes\n", sizeof(signed long)); printf("\tRanges from %li to %li\n\n", LONG_MIN, LONG_MAX); puts("unsigned long:"); printf("\tOccupies %i bytes\n", sizeof(unsigned long)); printf("\tRanges from %i to %lu\n\n", 0, ULONG_MAX); puts("float:"); printf("\tOccupies %i bytes\n", sizeof(float)); printf("\tRanges from +/-(1E%+i to 1E%+i) approx.\n", FLT_MIN_10_EXP, FLT_MAX_10_EXP); printf("\tPrecision is %i decimal digits approx.\n\n", FLT_DIG); puts("double:"); printf("\tOccupies %i bytes\n", sizeof(double)); printf("\tRanges from +/-(1E%+i to 1E%+i) approx.\n", DBL_MIN_10_EXP, DBL_MAX_10_EXP); printf("\tPrecision is %i decimal digits approx.\n\n", DBL_DIG); puts("long double:"); printf("\tOccupies %i bytes\n", sizeof(long double)); printf("\tRanges from +/-(1E%+i to 1E%+i) approx.\n", LDBL_MIN_10_EXP, LDBL_MAX_10_EXP); printf("\tPrecision is %i decimal digits approx.\n\n", LDBL_DIG); puts("pointer:"); printf("\tOccupies %i bytes\n", sizeof(void *)); puts(""); return; } With this computer and compiler, the simple C data types have the following characteristics: signed char: Occupies 1 byte (8 bits) Ranges from -128 to 127 unsigned char: Occupies 1 bytes (8 bits) Ranges from 0 to 255 signed short: Occupies 2 bytes Ranges from -32768 to 32767 unsigned short: Occupies 2 bytes Ranges from 0 to 65535 signed int: Occupies 4 bytes Ranges from -2147483648 to 2147483647 unsigned int: Occupies 4 bytes Ranges from 0 to 4294967295 signed long: Occupies 4 bytes Ranges from -2147483648 to 2147483647 unsigned long: Occupies 4 bytes Ranges from 0 to 4294967295 float: Occupies 4 bytes Ranges from +/-(1E-37 to 1E+38) approx. Precision is 6 decimal digits approx. double: Occupies 8 bytes Ranges from +/-(1E-307 to 1E+308) approx. Precision is 15 decimal digits approx. long double: Occupies 8 bytes Ranges from +/-(1E-307 to 1E+308) approx. Precision is 15 decimal digits approx. pointer: Occupies 4 bytes Integer types • In the examples we used the sizeof keyword to determine how many bytes are used to store each type. sizeof(unsigned int) or sizeof(x) • The names short and long can be misleading, on in the last example int and long were the same size. sizeof(short) sizeof(int) sizeof(long) data type variable ≤ ≤ Floating Point Numbers • Numbers like 1234.567 can be expressed in “scientific notation” as 1.234567 x 103, or +.1234567 e+4 • We let the decimal point float to the LH end of the mantissa – Such as representation is called floating point • We can use a similar method to generate a binary code, typically 4 bytes are used to store floating point N’s – The majority of bits are used for the mantissa and a few for the exponent. – Both parts are stored as 2’s complement • The float type is often poor precision (6 sig figs) far worse than a calculator – C also has a double precision floating point type , double, which typically uses 8 bytes mantissa exponent Characters • There is only one character type, char • This is defined (in ANSI C) to be a single byte. • Depending upon the context it can be treated as an integer, so there are signed and unsigned versions – char (-128 to +127) and – unsigned char (0 to 255) • A char variable holds ASCII codes as well as some escape characters – ‘\n’ = new line, ‘\t’ = tab, ‘\a’ = alert (beep), ‘\0’ = null • The null character has the code 0000000 (binary) and has a special role in strings. Names rules • If we wish to create a new variable, say a floating point variable called x, this is done by float x; • However there are restrictions on the names that we can use. – Can only include letters, digits or underscores ‘_’ – First character cannot be a digit – Upper and lower case are distinct (All upper used for #define) – Must not be the same as any of C’s 32 keywords • auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while – Is is also sensible not to use other common C identifiers, e.g. printf

DeclaringVariablesConstantsIt makes sense to use symbols for constants, e.g. x instead of.3.14159..., to save typing, avoid errors and improve readability.InC,all variablesmustbedeclaredbeforethey can be used. Typical declarations :We could define a variable.-int i,j,k;float pi=3.14159,-unsigned 1ong very_big_thing=1000000;butit is better C style to use a tdet ine#define PI 3.14159-char c;- char ch='a',NL="ln';This means that where ever "Pr' appears in the program, the pre--f1oatx,y-4E-6,z=0.0015f;processor substitutes*3.14159* The pre-processoris a program that processesthe source fle just before·Note that variables can be initialised (given athe compiler proper startsvalue) at their declaration, if desired.Conventionally such constants are in CAPITALSaauaator/."uvnames=r oea taooud中-u413544:2'owHTI200otp104e9T*petoW34

4 Declaring Variables • In C, all variables must be declared before they can be used. Typical declarations : – int i,j,k; – unsigned long very_big_thing=1000000; – char c; – char ch=‘a’,NL=‘\n’; – float x,y=4E-6,z=0.0015f; • Note that variables can be initialised (given a value) at their declaration, if desired. Constants • It makes sense to use symbols for constants, e.g. π instead of 3.14159., to save typing, avoid errors and improve readability • We could define a variable float pi=3.14159; but it is better C style to use a #define #define PI 3.14159 • This means that where ever “PI” appears in the program, the pre￾processor substitutes “3.14159” – The pre-processor is a program that processes the source file just before the compiler proper starts • Conventionally such constants are in CAPITALS /* Example: constant definition using #define */ #include #define PI 3.142 /* To change this to a more accurate value, (e.g. 3.14159265358979323846) throughout the program, only one line needs to be edited. */ main() { double r, c, ac, as, v; r = 5.678; printf("Radius = %f\n", r); c = 2.0 * PI * r; printf("Circle's circumference = %f\n", c); ac = PI * r * r; printf("Circle's area = %f\n", ac); as = 4.0 * PI * r * r; printf("Sphere's area = %f\n", as); v = 4.0/3.0 * PI * r * r * r; printf("Sphere's volume = %f\n", v); } define.c

已到末页,全文结束
刷新页面下载完整文档
VIP每日下载上限内不扣除下载券和下载次数;
按次数下载不扣除下载券;
注册用户24小时内重复下载只扣除一次;
顺序:VIP每日次数-->可用次数-->下载券;
相关文档