辅导案例-CS 159

欢迎使用51辅导,51作业君孵化低价透明的学长辅导平台,服务保持优质,平均费用压低50%以上! 51fudao.top
Chapter 4
Functions
CS 159 - C Programming
Functions
▪ 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 program.
int main(void)
{
// task 1
statementA;
statementB;
statementC;
// task 2
statementD;
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 data
Functions
Optional
Side effects
Optional
Parameters
Optional
Return Value
Standard Libraries
#include
int main(void)
{
...
scanf(…);
...
printf(…);
...
}
int scanf(…);
int printf(…);
...
int scanf(…)
{
...
return …;
}
int printf(…);
{
...
return …;
}
Declaration from stdio.h
Definition from linker
Standard Libraries
Library 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 Functions
math.h
Function Description
double ceil(double x); Round up value
double floor(double x); Round down value
double fabs(double x); Compute absolute value
double modf(double x, double *ip); Break into integer and fractional parts
double fmod(double x, double y); Compute remainder of division
double pow(double x, double y); Compute power
double sqrt(double x); Compute square root
double exp(double x); Compute exponential
double frexp(double x, int *exp); Split into fraction and exponent
double ldexp(double x, int n); Combine fraction and exponent
double log(double x); Compute natural logarithm
double log10(double x); Compute common logarithm
double sin(double x); Compute sine
double cos(double x); Compute cosine
double tan(double x); Compute tangent
double asin(double x); Compute arc-cosine
double acos(double x); Compute arc-sine
double atan(double x); Compute arc-tangent
double atan2(double y, double x); Compute arc-tangent of quotient
double sinh(double x); Compute hyperbolic sine
double cosh(double x); Compute hyperbolic cosine
double tanh(double x); Compute hyperbolic tangent
math.h
Constant Description
M_E The base of natural logarithms
M_LOG2E The logarithm to base 2 of M_E
M_LOG10E The logarithm to base 10 of M_E
M_LN2 The natural logarithm of 2
M_LN10 The natural logarithm of 10
M_PI Pi, the ratio of a circle's circumference to its diameter
M_PI_2 Pi divided by two
M_PI_4 Pi divided by four
M_1_PI The reciprocal of pi (1/pi)
M_2_PI Two times the reciprocal of pi
M_2_SQRTPI Two times the reciprocal of the square root of pi
M_SQRT2 The square root of two
M_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: 3
Area of a circle = 28.27
stdlib.h
Function Description
int abs(int n); Absolute value of integer
long labs(long n); Absolute value of long integer
div_t div(int num, int denom); Integer division
ldiv_t ldiv(long num, long denom); Long integer division
double atof(char *s); Convert string to floating-point
int atoi(char *s); Convert string to integer
long atol(char *s); Convert string to long integer
void* calloc(size_t nobj, size_t size); Allocate and clear memory block
void* malloc(size_t size); Allocate memory block
void* realloc(void *p, size_t size); Resize memory block
void free(void *p); Free memory block
int rand(); Generate pseudo-random number
void srand(unsigned int seed); Seed pseudo-random number generator
void abort(); Abort program
void exit(int status); Exit from program
int system(char *s); Perform operating system command
char getenv(char *name); Get environment string

#include
#include
#include
int main()
{
srand(time(NULL)); // provide the seed only once
printf("%d\n",rand());
printf("%d\n",rand());
printf("%d\n",rand());
printf("%d\n",rand());
return 0;
}
585352274
299854239
1733269956
198980185
Standard Libraries
Programming 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 Functions
Declaration – used in the global declaration section
Function Call – place in program where function is invoked
Definition – code that performs the processing
data-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 value
User-Defined Functions
#include
void greeting();
int main(void)
{
greeting();
return 0;
}
void greeting()
{
printf("Hello World\n");
return;
}
Side effect
No Parameter
No Return Value
User-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 effect
Parameter
Return 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 definition
Parameters
#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 once
num = 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 void.”
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
techniques
Pass 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 2
x 2 10
The 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 10
num 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: 3
Enter the second value: 4
First value: 3
Second 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.
Scope
Programming 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 function.
int 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 less
Programming 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)
main
input process
subprocess1 subprocess2
output
main
input 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 declarations
int 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 guess
int roll; // sum of two dice rolls
int result; // contains whether the numbers match
srand(time(NULL)); // seed random number generator
// receive the user's guess
guess = input();
// calculate sum of two dice rolls
roll = scale(1,6) + scale(1,6);
// determine whether the two numbers match
result = compare(guess, roll);
// output the results
output(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 response
printf("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 range
range = to - from + 1;
// return a random number scaled in that range
return 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 numbers
result = abs(num1 - num2); // 0 if they match
// scale that number to a 1 or 0 and reverse it
result = 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 roll
printf("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 result
printf("Do the numbers match? %c\n", answer);
return;
}
Please enter your guess: 7
The roll of two dice is: 9
Do the numbers match? N
Please enter your guess: 5
The roll of two dice is: 5
Do the numbers match? Y
Find 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);
}
51作业君

Email:51zuoyejun

@gmail.com

添加客服微信: abby12468