Skip to main content

辅导案例-CS 159

By May 15, 2020留学咨询

Chapter 4FunctionsCS 159 – C ProgrammingFunctions▪ Advantages• Program is easier to understand and manage• Program is easier to debug and maintain• Code can be reused in other programs• Encapsulation of local data (black box)Function – a named block of code (consisting of a header and a body) that performs a specific task within the main(void){// task 1statementA;statementB;statementC;// task 2statementD;statementE;statementF;return; }int main(void){task1();task2();}void task1(){statementA;statementB;statementC;return;}void task2(){statementD;statementE;statementF;return;}Functions▪ Calling function – function that makes the call▪ Passes zero or more pieces of data▪ Receives back zero or one piece of data as expression is evaluated▪ Called function – function that is called• Receives zero or more pieces of data• Processes the data (possible side effects)• Returns zero or one piece of dataFunctionsOptionalSide effectsOptionalParametersOptionalReturn ValueStandard Libraries#include int main(void){…scanf(…);…printf(…);…}int scanf(…);int printf(…);…int scanf(…){…return …;}int printf(…);{…return …;}Declaration from stdio.hDefinition from linkerStandard LibrariesLibrary Description Diagnostics Functions Character Handling Functions Localization Functions Mathematics Functions Nonlocal Jump Functions Signal Handling Functions Variable Argument List Functions Input/Output Functions General Utility Functions String Functions Date and Time Functionsmath.hFunction Descriptiondouble ceil(double x); Round up valuedouble floor(double x); Round down valuedouble fabs(double x); Compute absolute valuedouble modf(double x, double *ip); Break into integer and fractional partsdouble fmod(double x, double y); Compute remainder of divisiondouble pow(double x, double y); Compute powerdouble sqrt(double x); Compute square rootdouble exp(double x); Compute exponentialdouble frexp(double x, int *exp); Split into fraction and exponentdouble ldexp(double x, int n); Combine fraction and exponentdouble log(double x); Compute natural logarithmdouble log10(double x); Compute common logarithmdouble sin(double x); Compute sinedouble cos(double x); Compute cosinedouble tan(double x); Compute tangentdouble asin(double x); Compute arc-cosinedouble acos(double x); Compute arc-sinedouble atan(double x); Compute arc-tangentdouble atan2(double y, double x); Compute arc-tangent of quotientdouble sinh(double x); Compute hyperbolic sinedouble cosh(double x); Compute hyperbolic cosinedouble tanh(double x); Compute hyperbolic tangentmath.hConstant DescriptionM_E The base of natural logarithmsM_LOG2E The logarithm to base 2 of M_EM_LOG10E The logarithm to base 10 of M_EM_LN2 The natural logarithm of 2M_LN10 The natural logarithm of 10M_PI Pi, the ratio of a circle’s circumference to its diameterM_PI_2 Pi divided by twoM_PI_4 Pi divided by fourM_1_PI The reciprocal of pi (1/pi)M_2_PI Two times the reciprocal of piM_2_SQRTPI Two times the reciprocal of the square root of piM_SQRT2 The square root of twoM_SQRT1_2 The reciprocal of the square root of two #include #include int main(void){float radius;float area;printf(“Enter the radius of a circle: “);scanf(“%f”, &radius);area = M_PI * pow(radius,2);printf(“Area of a circle = %5.2f\n”, area);return 0;}Enter the radius of a circle: 3Area of a circle = 28.27stdlib.hFunction Descriptionint abs(int n); Absolute value of integerlong labs(long n); Absolute value of long integerdiv_t div(int num, int denom); Integer divisionldiv_t ldiv(long num, long denom); Long integer divisiondouble atof(char *s); Convert string to floating-pointint atoi(char *s); Convert string to integerlong atol(char *s); Convert string to long integervoid* calloc(size_t nobj, size_t size); Allocate and clear memory blockvoid* malloc(size_t size); Allocate memory blockvoid* realloc(void *p, size_t size); Resize memory blockvoid free(void *p); Free memory blockint rand(); Generate pseudo-random numbervoid srand(unsigned int seed); Seed pseudo-random number generatorvoid abort(); Abort programvoid exit(int status); Exit from programint system(char *s); Perform operating system commandchar getenv(char *name); Get environment string…#include #include #include int main(){srand(time(NULL)); // provide the seed only onceprintf(“%d\n”,rand());printf(“%d\n”,rand());printf(“%d\n”,rand());printf(“%d\n”,rand());return 0;}5853522742998542391733269956198980185Standard LibrariesProgramming Standards: ▪ Any #include pre-processor directives must go at the top of your program, just below the program header comment.▪ You are only permitted to use the standard C libraries functions mentioned in the book or introduced in class up to the current chapter.User-Defined FunctionsDeclaration – used in the global declaration sectionFunction Call – place in program where function is invokedDefinition – code that performs the processingdata-type name (formal-parameter-list);name(actual-parameter-list);data-type name (formal-parameter-list){// declare local variables…// statements to process…return expression; // (or use return; if void)}x = name(actual-parameter-list);User-Defined Functions/************************************************************** Function: function name* Description: brief description of the function* Parameters: variable1 name, data type, and description* variable2 name, data type, and description* Return: data type and description*************************************************************/Programming Standards: Every user-define function (not including main) must be preceded with a header comment.User-Defined Functions▪ Can make use of any of these optional elements:• Parameter passing• Side effects• Return valueUser-Defined Functions#include void greeting();int main(void){greeting();return 0;}void greeting(){printf(“Hello World\n”);return;}Side effectNo ParameterNo Return ValueUser-Defined Functions#include int timestwo(int num);int main(void){int x = 3;x = timestwo(x);return 0;}int timestwo(int num){int y;y = num * 2;return y;}No Side effectParameterReturn Value#include char letter1();char letter2();int main(){printf(“%c\n”,letter1());return 0;}char letter1(){printf(“b”);printf(“%c”,letter2());printf(“%c”,letter2());return ‘a’;}char letter2(){printf(“a”);return ‘n’;}Parameters▪ Formal parameters are variables that are declared in the header of the function definition▪ Actual parameters are the expressions in the calling statement▪ Formal and actual parameters must match exactly in order, type, and number▪ Variables names in the calling statement do not need to match the variable names in the function definitionParameters#include #include void process(int num1, int num2, int num3);int main(void){int x = 4;int y = 3;process(x + 2, pow(7,2), y);…return 0;}void process(int num1, int num2, int num3){…}Parameters#include void process(int num, char answer, float rate);int main(void){char x = ‘Y’;float y = 4.2;int z = 3;process(x, y, z);…return 0;}void process(int num, char answer, float rate){…}Don’t do this!#include int calc(int z);int main(){int x = 4;int y = 3;x = calc(x);y = calc(x) + calc(y);printf(“result: %d\n”, x + calc(y));return 0;}int calc(int z){z = z + 5 / 2;return z;}#include int calc(int num);int main(){int x = 5;x = calc(calc(calc(x)));printf(“result = %d\n”,x);return 0;}int calc(int num){return num + 1;}#include int adjust(int y, int x);int main(){int x = 5;int y = 4;int z;z = adjust(x++, y–);printf(“x = %d, y = %d, z = %d\n”, x, y, z);return 0;}int adjust(int y, int x){x++;y++;return x + y;}#include #include #include int scale(int from, int to);int main(){int num;srand(time(NULL)); // provide the seed only oncenum = scale(10,20);printf(“%d\n”,num);return 0;}int scale(int from, int to){int range;range = to – from + 1;return rand() % range + from;}Return Statement▪ The return value should match the type of the function▪ The return statement can return no more than one value▪ Any expression can be returned that can be reduced to a single value“C Programmers never die.They are just returned vo
id.”Programming Standards: Every function should have exactly one return statement, even if it is void, and it must be the last statement in the function. Inter-Function Communication▪ Downward flow• Pass by value – parameters are passed to the function, but the values of the variables remain unchanged▪ Upward flow• Return statement – only a single value can be returned• Pass by address – the address of a variable is passed to the function and the value of the variable can be changed (C’s version of pass by reference)▪ Bi-directional flow – can use any combination of these techniquesPass by Value#include void process(int x);int main(){int num = 2;process(num);printf(“main %d\n”,num);return 0;}void process(int x){x = x * 5;printf(“process %d\n”,x);return;}num 2x 2 10The value of num is copied into x which is a different variable.Pass by Address#include void process(int *x);int main(){int num = 2;process(&num);printf(“main %d\n”,num);return 0;}void process(int *x){*x = *x * 5;printf(“process %d\n”,*x);return;}num 2 10num and x both share the same memory address. If you change x you will also change num.Pass by Address▪ Use a & in front of the variable name in the calling statement (accesses the address)▪ Use a * after the data type in the formal parameter in the function header (access data at the address)▪ Use a * in front of the variable in the function body to store the data indirectly (access data at the address)Programming Standards: Passing parameters by address should be minimized and only used when more than one value needs to be revised and the altered values need to be retained in the calling function after the called function terminates.#include void getValues(int *a, int *b);int main(){int x;int y;getValues(&x,&y);printf(“First value: %d\n”, x);printf(“Second value: %d\n”, y);return 0;}void getValues(int *a, int *b){printf(“Enter the first value: “);scanf(“%d”, a);printf(“Enter the second value: “);scanf(“%d”, b);return;}Enter the first value: 3Enter the second value: 4First value: 3Second value: 4#include void swap(int *num1, int *num2);int main(void){int x = 5;int y = 2;swap(&x, &y);printf(“x: %d, y: %d\n”,x,y);return 0;}void swap(int *num1, int *num2){int hold;hold = *num1;*num1 = *num2;*num2 = hold;return;}#include void test (int x, int *y);int main(){int a = 7;int b = 8;test(b, &a);printf(“%d %d\n”, a, b);return 0;}void test (int a, int *b){ a = 9;*b = a;return;}#include char letter1(char a, char b);void letter2(char *x, char y);int main(){printf(“%c\n”, letter1(‘n’ – 1,’a’));return 0;}char letter1(char a, char b){printf(“%c”,a);letter2(&b,’s’);letter2(&b,’s’);letter2(&b,’p’);return b;}void letter2(char *x, char y){*x = ‘i’;printf(“%c%c%c”, *x, y, y);return;}Scope▪ Variables and functions defined within a block cease to exist when the block ends▪ Prevents unwanted interaction between a code block and the outside world (black box concept)Scope – the region of a program in which a defined object (variable or function) is available.ScopeProgramming Standards:▪ Global variables (which are declared before the main function) are not permitted. If variables need to be shared with other functions, you will need to pass them as parameters.▪ Do not reuse any identifier that is inside two objects that have overlapping scope. Always pick separate names to avoid confusion.▪ All function declarations should have a global scope. Do not declare a function inside of another main(void){int x = 5;{int x = 2;printf(“x: %d\n”,x);}process(x);printf(“x: %d\n”,x);return 0;}void process(int x){x = 4;printf(“x: %d\n”,x);return;}Top-Down Design▪ Top-Down Design – program is divided into a main module and its related modules▪ Factoring – each module is further divided into functions as necessary until they are implicitly understood without further division• Cohesion – the degree to which the elements of a module belong together (maximize this)• Coupling – the degree that one module is dependent on another module (minimize this)Top-Down Design▪ A good rule of thumb is that a single function should not contain no more than 20-30 lines of code▪ It is better to have more separate functions than lessProgramming Standards: ▪ The only statements allowed in the main program are the declaration of variables needed to be passed between function, the functions called by main and a minimum amount of control code to direct the central processing.▪ Each function should be functionally cohesive such that it completes only a single fundamental task. Do not combine several unrelated tasks in a function.Structure Charts▪ Overall design is completed before any code is written▪ Chart only shows the functions called, not any code▪ Common functions contain cross hatch in lower right corner (only have to include it once the first time it is called)maininput processsubprocess1 subprocess2outputmaininput scale compare output/******************************************************* Assignment: HW 8* Lab Section: Monday 8:30 SC 189* Description: Receives a user’s guess and displays* the sum of two simulated dice rolls* and determines if the two numbers match.* Programmers: [email protected]******************************************************/#include #include #include #include // function declarationsint input(void);int scale(int from, int to);int compare(int num1, int num2);void output(int roll, int result);int main(){int guess; // contains the user’s guessint roll; // sum of two dice rollsint result; // contains whether the numbers matchsrand(time(NULL)); // seed random number generator// receive the user’s guessguess = input();// calculate sum of two dice rollsroll = scale(1,6) + scale(1,6);// determine whether the two numbers match result = compare(guess, roll);// output the resultsoutput(roll, result);return 0;}/******************************************************* Function: input* Description: Receives a number from the user.* Parameters: none* Return: int containing the user’s guess.******************************************************/int input(void){int guess; // value of the user’s guess// Prompt the user and receive his responseprintf(“Please enter your guess: “);scanf(“%d”,&guess);return guess;}/******************************************************* Function: scale* Description: Generates a random number scale* within the specified range.* Parameters: from – the lower limit* to – the upper limit* Return: int containing the random number******************************************************/int scale(int from, int to){int range; // holds the size of the range// determine the size of the rangerange = to – from + 1;// return a random number scaled in that rangereturn rand() % range + from;}/******************************************************* Function: compare* Description: Compares whether two numbers are the* same and returns a boolean value as* the result.* Parameters: num1 – the first number to compare* num2 – the second number to compare* Return: int containing the result (1 or 0)******************************************************/int compare(int num1, int num2){int result; // result of the comparison// find the difference between the two numbersresult = abs(num1 – num2); // 0 if they match// scale that number to a 1 or 0 and reverse itresult = 1 – ((result + 2) % (result + 1));return result;}/******************************************************* Function: output* Description: Displays whether the user’s guess and* the sum of the two dice rolls match.* Parameters: roll – the sum of the two dice rolls* result – boolean value of the result* Return: none******************************************************/void output(int roll, int result){char answer; // Either ‘Y’ or ‘N’ // display the computer’s dice rollprintf(“The roll of two dice is: %d\n”,roll);// translate boolean value into a ‘Y’ or ‘N’answer = ‘Y’ * result + ‘N’ * (1 – result);// print out the resultprintf(“Do the numbers match?
%c\n”, answer);return;}Please enter your guess: 7The roll of two dice is: 9Do the numbers match? NPlease enter your guess: 5The roll of two dice is: 5Do the numbers match? YFind the Bugs (8)#include void power(int, int)int main(void){x = power(2, 8);printf(“%d/n”,x);return 0;}void power(int num1; int num2);{return pow(num1, num2);}


Author admin

More posts by admin

Leave a Reply