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

英格兰萨里大学:《C语言》课程教学资源(讲义)Lecture 12 - Basics of Functions

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

snLecture 12Basics of Functionsoadom.Weshouldallbefamiliarwithmathematicalfunctionsf(x) = x2- 3x + 50- heref denotes the function-xis called its argument- and the expression x2. 3x + 5 is an algorithm whichdescribes howtocalculate the functions valuet.NotethatxismerelyaplaceholderandwecouldFileWritef(z)=z2.3z+5orf(p+1) =(p+1)23(p+1)+5Daa SucyCasestidcloterynuntergmneraBasicsofFunctionsBasics of FunctionsWecanalsohavefunctionsofseveralvariables.Sowecanwriteafunctionwhichcalculatesg(X,y,z) = x2* y2+ z2the square ofa numberas where there are several variables x.y,zfloat square(float x).Somemathematicalfunctionshavespecialreturn x*x:symbols e.g.ex,log x, sin x,Ixletc but theprinciple remains the same which is like f(x) = x2.InCwehaveasimilaridea this takes a float parameter x (which is the placeFunctionstaketheformofholder)and returns anotherfloat valueretum type][tunction mame] ([argusent liat_])Bhenlade*,turn J fnctions neterraBasics ofFunctions+金.Thefunction is“called"asfollowsfloat y.z-3.0f;y-square(z) ;Noticethat wehave used Zas the argumentand haveassigned thereturn value to y..Diagrammatically:2e馆E囍:Theargumentzis cpiedtoe1parameter (placehdider) :xcopied to

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 12 Lecture 12 Basics of Functions • We should all be familiar with mathematical functions f(x) = x2 - 3x + 5 – here f denotes the function – x is called its argument – and the expression x2 - 3x + 5 is an algorithm which describes how to calculate the functions value • Note that x is merely a placeholder and we could write f(z) = z2 - 3z + 5 or f(p+1) = (p+1)2 - 3(p+1) + 5 Basics of Functions • We can also have functions of several variables g(x,y,z) = x2 + y2 + z2 – where there are several variables x,y,z • Some mathematical functions have special symbols e.g. ex, log x, sin x, |x| etc but the principle remains the same • In C we have a similar idea • Functions take the form of [return type] [function name] ( [argument list.] ) { /* Body of the function where calculations are made*/ return ; /* functions returns some value*/ } Basics of Functions • So we can write a function which calculates the square of a number as float square(float x) { return x*x; } • which is like f(x) = x2 – this takes a float parameter x (which is the place holder) and returns another float value Basics of Functions • The function is “called” as follows float y, z=3.0f; y=square(z); • Notice that we have used Z as the argument and have assigned the return value to y. • Diagrammatically: main z y x calculate x*x copy copy The argument z is copied to the parameter (placeholder) x The return value is copied to y /* Example: simple functions */ /* Functions taking one or more arguments and returning a value */ #include /* Function prototypes: */ float square(float x); /* computes x squared */ float cube(float x); /* computes x cubed */ float power(float x, int n); /* computes x to power n >= 0 */ main() { float X; int N; printf("Enter a floating point number: "); scanf("%f", &X); printf("Enter an integer >= 0: "); scanf("%i", &N); printf("The square of %f is %f\n", X, square(X)); printf("The cube of %f is %f\n", X, cube(X)); printf("%f to the power %i is %f\n", X, N, power(X, N)); } /* Function definitions: */ float square(float x) /* computes x squared */ { return x * x; } float cube(float x) /* computes x cubed */ { return x * x * x; } float power(float x, int n) /* computes x to power n >= 0*/ { /* Note: no check is made for n >= 0! */ float t = 1; while (n > 0) { t *= x; n-; } return t; } /* Example: simple functions */ /* Functions taking one or more arguments and returning a value */ #include /* Function prototypes: */ float square(float x); /* computes x squared */ float cube(float x); /* computes x cubed */ float power(float x, int n); /* computes x to power n >= 0 */ main() { float X; int N; printf("Enter a floating point number: "); scanf("%f", &X); printf("Enter an integer >= 0: "); scanf("%i", &N); printf("The square of %f is %f\n", X, square(X)); printf("The cube of %f is %f\n", X, cube(X)); printf("%f to the power %i is %f\n", X, N, power(X, N)); } /* Function definitions: */ float square(float x) /* computes x squared */ { return x * x; } float cube(float x) /* computes x cubed */ { return x * x * x; } float power(float x, int n) /* computes x to power n >= 0*/ { /* Note: no check is made for n >= 0! */ float t = 1; while (n > 0) { t *= x; n-; } return t; } funct1.c funct1.c

FunctionPrototypesFunctionPrototypes.To avoid this C has function prototypes which go.Recall thatwemustdeclarevariables (primarilynear the start, while thefunction definitionstogivethematype)beforeusingthem.usuallycomeaftermainSimilarly wemustdeclare functions before usingIdertifernot actualy teeded.egthemprototype30Te·We could dothisbyputting allfunctions attheNotethe semicolonidmain()startoftheprogram(beforemain)callyangaare(z) ;.Howeverthis has disadvantages- all the details are given before the general outineefinitior-twofunctioncouldcalleachotherso itwouldbeemicoloimpossible to get them in the right orderFunctionswithnoReturnValueFunctionswithnoArguments·Sometimesa function has no argument, butAgain,void is used to denotea lack of returnreturns a valuetype for a function.:To copewiththis thevoidkeyword is usedThe keyword return.VOID is used likeadatatypebut meansisusedwithouta"absenceoftype"or"notype"followingexpressionint rand(void) :F. Fetis tiarig torcanbeomitted ifPfunct3.cint i;your lazy/sloppyRi-rand():void stars(int n);.Theemptyparenthesesfunct2.c()are needed!stars(3);FunctionswithnoArgumentsMultipleReturnStatementsandnoReturnValue.It issometimesconvenienttohavemultiplereturnsvoid print20stars(vo1d) ;e.g. in an if..else or switch statementfunct5.cprint20stara():saint2

2 Function Prototypes • Recall that we must declare variables (primarily to give them a type) before using them. • Similarly we must declare functions before using them • We could do this by putting all functions at the start of the program (before main) • However this has disadvantages – all the details are given before the general outline – two function could call each other so it would be impossible to get them in the right order Function Prototypes • To avoid this C has function prototypes which go near the start, while the function definitions usually come after main • eg float square(float x); void main() { y=square(z); } float square(float x) { return x*x; } prototype Note the semicolon definition call no semicolon Identifier not actually needed Functions with no Arguments • Sometimes a function has no argument, but returns a value • To cope with this the void keyword is used • VOID is used like a data type but means “absence of type” or “no type” int rand(void); . int i; i=rand(); • The empty parentheses ( ) are needed! /* Example: simple functions */ /* Function taking no arguments but returning a value */ #include #include /* for rand */ /* The prototype of rand is int rand(void); */ main() { int n; puts("Some random numbers:"); for (n = 0; n #include /* for rand */ /* The prototype of rand is int rand(void); */ main() { int n; puts("Some random numbers:"); for (n = 0; n void stars(int n); /* print a line of n stars */ main() { int s; puts("How many stars?"); scanf("%i", &s); stars(s); } void stars(int n) /* print a line of n stars */ { while (n- > 0) putchar('*'); putchar('\n'); return; } /* Example: simple functions */ /* Function taking an argument but returning no value */ #include void stars(int n); /* print a line of n stars */ main() { int s; puts("How many stars?"); scanf("%i", &s); stars(s); } void stars(int n) /* print a line of n stars */ { while (n- > 0) putchar('*'); putchar('\n'); return; } funct3.c funct3.c Functions with no Arguments and no Return Value void print20stars(void); . print20stars(); /* Example: simple functions */ /* Function taking no arguments and returning no value */ #include void print20stars(void); /* print a line of 20 stars */ main() { int k; for (k = 0; k void print20stars(void); /* print a line of 20 stars */ main() { int k; for (k = 0; k int pins(int tn); /* IC pins lookup */ main() { int ic, p; printf("Enter an IC type number: "); scanf("%i", &ic); p = pins(ic); if (!p) printf("IC type %i is not recognised.\n", ic); else printf("IC type %i has %i pins.\n", ic, p); } /* Example: simple functions */ /* Function with multiple return statements */ #include int pins(int tn); /* IC pins lookup */ main() { int ic, p; printf("Enter an IC type number: "); scanf("%i", &ic); p = pins(ic); if (!p) printf("IC type %i is not recognised.\n", ic); else printf("IC type %i has %i pins.\n", ic, p); } int pins(int tn) /* IC pins lookup */ { /* Returns the number of pins for an IC of type number tn. If the type is not recognised, returns zero. */ switch (tn) { case 555: case 741: case 748: return 8; case 556: case 7400: case 7414: return 14; case 7448: case 7485: return 16; case 6502: case 6800: case 8085: case 8088: return 40; default: return 0; /* easily tested */ } } int pins(int tn) /* IC pins lookup */ { /* Returns the number of pins for an IC of type number tn. If the type is not recognised, returns zero. */ switch (tn) { case 555: case 741: case 748: return 8; case 556: case 7400: case 7414: return 14; case 7448: case 7485: return 16; case 6502: case 6800: case 8085: case 8088: return 40; default: return 0; /* easily tested */ } } funct5.c funct5.c

FunctionsCanpeoserCall Functions***oedede epd -/Functions need notbecalled directly from mainroneyamsFru Baan/.ien+ap./ IProo eep Functions can becalledfromanywhere,even s wy de mounw ndeachotherp 4- This allows us to break upa job into manageable aarr馆partsntumetwTe01MerryChristmas!ew:e的n联PeBwFunction Libraries.:Itsveryuseful tohave librariesofcommon..functions.eg functions which weve used extensively.The headerfile (*.h)contains theprototypes- stdio.h standard input and output functions*string.h string manipulation functionsmath.h common mathematical functions1mWhy doesn't this work(int mum)funct6.csain(ptinte (-tsin)m..x)Preturmprinef ("lnleguit-tiln',nunprinef(-lnguane_it) eguard ti)n-3

3 Functions Can Call Functions • Functions need not be called directly from main • Functions can be called from anywhere, even each other – This allows us to break up a job into manageable parts * *** ***** ******* ********* *********** ************* *************** ***************** * * ******* ***** *** Merry Christmas! * *** ***** ******* ********* *********** ************* *************** ***************** * * ******* ***** *** Merry Christmas! /* Example: draws a Christmas card */ /* Function calling another function */ #include void draw_tree(void); /* draws a tree */ void starline(int sp, int st); /* prints sp spaces then st stars */ main() { draw_tree(); puts(" Merry Christmas!"); } void draw_tree(void) /* draws a tree */ { int i; for (i = 1; i 1; i -= 2) starline(9 - i/2, i); putchar('\n'); return; } void starline(int sp, int st) /* prints sp spaces then st stars */ { while (sp- > 0) putchar(' '); while (st- > 0) putchar('*'); putchar('\n'); return; } /* Example: draws a Christmas card */ /* Function calling another function */ #include void draw_tree(void); /* draws a tree */ void starline(int sp, int st); /* prints sp spaces then st stars */ main() { draw_tree(); puts(" Merry Christmas!"); } void draw_tree(void) /* draws a tree */ { int i; for (i = 1; i 1; i -= 2) starline(9 - i/2, i); putchar('\n'); return; } void starline(int sp, int st) /* prints sp spaces then st stars */ { while (sp- > 0) putchar(' '); while (st- > 0) putchar('*'); putchar('\n'); return; } xmascard.c xmascard.c Function Libraries • Its very useful to have libraries of common functions. eg functions which weve used extensively • The headerfile (*.h) contains the prototypes – stdio.h standard input and output functions – string.h string manipulation functions – math.h common mathematical functions /* Example: mathematical functions in the library */ /* At the Unix prompt, enter 'man math' for details */ #include #include /* contains function prototypes etc. */ main() { printf("fabs(-2.6) = %f\n", fabs(-2.6)); /* absolute value */ printf("ceil(7.5) = %f\n", ceil(7.5)); /* round up */ printf("floor(7.5) = %f\n\n", floor(7.5)); /* round down */ printf("HUGE_VAL = %lf\n", HUGE_VAL); /* "infinity" */ printf("sqrt(0.5) = %f\n", sqrt(0.5)); /* square root */ printf("fmod(2.7, 0.5) = %f\n\n", fmod(2.7, 0.5)); /* remainder */ printf("sin(0.5) = %f\n", sin(0.5)); /* sine */ printf("cos(0.5) = %f\n", cos(0.5)); /* cosine */ printf("tan(0.5) = %f\n\n", tan(0.5)); /* tangent */ printf("acos(0.5) = %f\n", acos(0.5)); /* arccosine */ printf("asin(0.5) = %f\n", asin(0.5)); /* arcsine */ printf("atan(0.5) = %f\n", atan(0.5)); /* arctangent */ printf("atan2(1, 2) = %f\n\n", atan2(1, 2)); /* arctangent */ printf("exp(0.5) = %f\n", exp(0.5)); /* exponential */ printf("sinh(0.5) = %f\n", sinh(0.5)); /* hyperbolic sine */ printf("cosh(0.5) = %f\n", cosh(0.5)); /* hyperbolic cosine */ printf("tanh(0.5) = %f\n\n", tanh(0.5)); /* hyperbolic tangent */ printf("log(0.5) = %f\n", log(0.5)); /* natural logarithm */ printf("log10(0.5) = %f\n\n", log10(0.5)); /* base 10 logarithm */ printf("pow(0.5, 2.4) = %f\n\n", pow(0.5, 2.4)); /* power */ } /* Example: mathematical functions in the library */ /* At the Unix prompt, enter 'man math' for details */ #include #include /* contains function prototypes etc. */ main() { printf("fabs(-2.6) = %f\n", fabs(-2.6)); /* absolute value */ printf("ceil(7.5) = %f\n", ceil(7.5)); /* round up */ printf("floor(7.5) = %f\n\n", floor(7.5)); /* round down */ printf("HUGE_VAL = %lf\n", HUGE_VAL); /* "infinity" */ printf("sqrt(0.5) = %f\n", sqrt(0.5)); /* square root */ printf("fmod(2.7, 0.5) = %f\n\n", fmod(2.7, 0.5)); /* remainder */ printf("sin(0.5) = %f\n", sin(0.5)); /* sine */ printf("cos(0.5) = %f\n", cos(0.5)); /* cosine */ printf("tan(0.5) = %f\n\n", tan(0.5)); /* tangent */ printf("acos(0.5) = %f\n", acos(0.5)); /* arccosine */ printf("asin(0.5) = %f\n", asin(0.5)); /* arcsine */ printf("atan(0.5) = %f\n", atan(0.5)); /* arctangent */ printf("atan2(1, 2) = %f\n\n", atan2(1, 2)); /* arctangent */ printf("exp(0.5) = %f\n", exp(0.5)); /* exponential */ printf("sinh(0.5) = %f\n", sinh(0.5)); /* hyperbolic sine */ printf("cosh(0.5) = %f\n", cosh(0.5)); /* hyperbolic cosine */ printf("tanh(0.5) = %f\n\n", tanh(0.5)); /* hyperbolic tangent */ printf("log(0.5) = %f\n", log(0.5)); /* natural logarithm */ printf("log10(0.5) = %f\n\n", log10(0.5)); /* base 10 logarithm */ printf("pow(0.5, 2.4) = %f\n\n", pow(0.5, 2.4)); /* power */ } math.c math.c #include void square_it(int num); main() { int x = 6; printf("[main] x = %i\n", x); square_it(x); printf("\n[main] x squared = %i\n", x); return; } void square_it(int num) { printf("\n[square_it] num = %i\n", num); num *= num; /* multiply num by itself */ printf("\n[square_it] num squared = %i\n", num); return; } #include void square_it(int num); main() { int x = 6; printf("[main] x = %i\n", x); square_it(x); printf("\n[main] x squared = %i\n", x); return; } void square_it(int num) { printf("\n[square_it] num = %i\n", num); num *= num; /* multiply num by itself */ printf("\n[square_it] num squared = %i\n", num); return; } Why doesn’t this work funct6.c funct6.c

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