介绍
在本实验中,你将学习如何在 C 编程中创建和使用函数。实验涵盖了声明和定义函数的基本概念、理解函数参数、从函数返回值、处理无返回值函数(void functions)以及练习函数的使用。你将通过动手示例和练习探索这些主题,掌握编写模块化和可重用 C 代码的技能。
实验首先介绍函数声明和定义的基础知识,演示如何创建和调用简单的函数。然后深入探讨函数参数的理解,展示如何将不同的数据类型作为输入传递给函数。实验还涵盖了返回值的概念,指导你如何从函数中返回数据。此外,实验还探讨了无返回值函数(void functions)的使用,这些函数不返回任何值。最后,你将有机会通过各种练习来实践和应用所学的概念。
声明和定义函数
在这一步中,你将学习如何在 C 编程中声明和定义函数。函数是组织和模块化代码的基本构建块。
让我们首先在 ~/project 目录下创建一个名为 functions_demo.c 的新文件:
cd ~/project
touch functions_demo.c
接下来,编写一个简单的函数声明和定义:
#include <stdio.h>
// 函数声明(原型)
void greet(char* name);
// 主函数
int main() {
// 调用函数
greet("LabEx User");
return 0;
}
// 函数定义
void greet(char* name) {
printf("Hello, %s! Welcome to C programming.\n", name);
}
让我们分解关键部分:
void greet(char* name)是函数声明(原型)- 该函数接受一个字符指针(字符串)作为参数
void表示该函数不返回值- 在
main()中,我们调用该函数并传入参数 - 函数定义位于主函数之后,实现了实际的逻辑
编译并运行程序:
gcc functions_demo.c -o functions_demo
./functions_demo
示例输出:
Hello, LabEx User! Welcome to C programming.
函数的作用包括:
- 将代码组织成可重用的块
- 提高代码的可读性
- 减少重复
- 模块化你的程序
理解函数参数
在这一步中,你将学习如何在 C 编程中使用函数参数。函数参数允许你将数据传递到函数中,从而使函数更加灵活和可重用。
让我们在 ~/project 目录下创建一个名为 function_arguments.c 的新文件:
cd ~/project
touch function_arguments.c
接下来,编写一个程序来演示不同类型的函数参数:
#include <stdio.h>
// 带有多个参数的函数
int calculate_rectangle_area(int length, int width) {
return length * width;
}
// 带有浮点数参数的函数
float convert_celsius_to_fahrenheit(float celsius) {
return (celsius * 9/5) + 32;
}
int main() {
// 使用整数参数
int length = 5;
int width = 3;
int area = calculate_rectangle_area(length, width);
printf("Rectangle Area: %d square units\n", area);
// 使用浮点数参数
float celsius = 25.0;
float fahrenheit = convert_celsius_to_fahrenheit(celsius);
printf("%.1f°C is %.1f°F\n", celsius, fahrenheit);
return 0;
}
让我们分解关键概念:
- 函数可以接受多个不同类型的参数
calculate_rectangle_area()接受两个整数参数convert_celsius_to_fahrenheit()接受一个浮点数参数- 在 C 语言中,参数是按值传递的(会创建一个副本)
- 函数可以在其计算中使用这些参数
编译并运行程序:
gcc function_arguments.c -o function_arguments
./function_arguments
示例输出:
Rectangle Area: 15 square units
25.0°C is 77.0°F
关于函数参数的关键点:
- 参数为函数提供输入
- 你可以传递变量或直接值
- 参数的数量和类型必须与函数声明匹配
- 参数使函数更加通用和可重用
从函数返回值
在这一步中,你将学习如何在 C 编程中从函数返回值。返回值允许函数计算结果并将其发送回调用代码。
让我们在 ~/project 目录下创建一个名为 function_returns.c 的新文件:
cd ~/project
touch function_returns.c
接下来,编写一个程序来演示不同类型的返回值:
#include <stdio.h>
// 返回整数的函数
int square(int number) {
return number * number;
}
// 返回浮点数的函数
float calculate_average(int a, int b, int c) {
return (float)(a + b + c) / 3;
}
// 返回字符的函数
char get_grade(int score) {
if (score >= 90) return 'A';
else if (score >= 80) return 'B';
else if (score >= 70) return 'C';
else if (score >= 60) return 'D';
else return 'F';
}
int main() {
// 使用整数返回值
int num = 7;
int squared = square(num);
printf("Square of %d is %d\n", num, squared);
// 使用浮点数返回值
int math = 85, science = 92, english = 78;
float average = calculate_average(math, science, english);
printf("Average score: %.2f\n", average);
// 使用字符返回值
int student_score = 85;
char grade = get_grade(student_score);
printf("Student score %d gets grade %c\n", student_score, grade);
return 0;
}
让我们分解关键概念:
- 函数可以返回不同的数据类型
square()返回一个整数结果calculate_average()返回一个浮点数get_grade()返回一个字符return关键字将值发送回调用函数- 返回类型必须与函数声明匹配
编译并运行程序:
gcc function_returns.c -o function_returns
./function_returns
示例输出:
Square of 7 is 49
Average score: 85.00
Student score 85 gets grade B
关于返回值的关键点:
- 返回值允许函数计算结果并发送回结果
- 根据函数的用途使用适当的返回类型
- 你可以直接使用返回值或将其存储在变量中
- 返回值使函数更强大和灵活
处理无返回值函数(Void Functions)
在这一步中,你将学习 C 编程中的无返回值函数(void functions)。无返回值函数执行操作而不返回值,适用于不需要返回结果的任务。
让我们在 ~/project 目录下创建一个名为 void_functions.c 的新文件:
cd ~/project
touch void_functions.c
接下来,编写一个程序来演示无返回值函数:
#include <stdio.h>
// 无返回值函数,用于打印欢迎信息
void print_welcome() {
printf("Welcome to the C Programming Lab!\n");
}
// 带参数的无返回值函数,用于显示学生信息
void display_student_info(char* name, int age) {
printf("Student Name: %s\n", name);
printf("Student Age: %d\n", age);
}
// 无返回值函数,用于绘制简单图案
void draw_pattern(int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("* ");
}
printf("\n");
}
}
int main() {
// 调用无返回值函数
print_welcome();
// 带参数的无返回值函数
char* student_name = "LabEx User";
int student_age = 25;
display_student_info(student_name, student_age);
// 带图案的无返回值函数
int pattern_size = 3;
printf("\nDrawing a %dx%d pattern:\n", pattern_size, pattern_size);
draw_pattern(pattern_size);
return 0;
}
让我们分解关键概念:
- 无返回值函数的返回类型为
void - 它们执行操作而不返回值
print_welcome()简单地打印一条消息display_student_info()接受参数并打印信息draw_pattern()使用嵌套循环创建视觉图案- 无返回值函数像普通函数一样被调用
- 不能在无返回值函数中使用带值的
return
编译并运行程序:
gcc void_functions.c -o void_functions
./void_functions
示例输出:
Welcome to the C Programming Lab!
Student Name: LabEx User
Student Age: 25
Drawing a 3x3 pattern:
* * *
* * *
* * *
关于无返回值函数的关键点:
- 用于不需要返回值的操作
- 可以接受参数
- 适用于打印、日志记录或执行特定任务
- 帮助组织和模块化代码
- 不能使用
return返回值
练习函数使用
在这最后一步中,你将通过创建一个综合程序来应用所学的 C 语言函数知识,该程序演示了多种函数类型及其用法。
让我们在 ~/project 目录下创建一个名为 calculator.c 的文件:
cd ~/project
touch calculator.c
接下来,编写一个实现简单计算器的程序,其中包含各种函数:
#include <stdio.h>
// 加法函数
int add(int a, int b) {
return a + b;
}
// 减法函数
int subtract(int a, int b) {
return a - b;
}
// 乘法函数
int multiply(int a, int b) {
return a * b;
}
// 除法函数,包含错误处理
float divide(int a, int b) {
if (b == 0) {
printf("Error: Division by zero!\n");
return 0;
}
return (float)a / b;
}
// 无返回值函数,显示计算器菜单
void display_menu() {
printf("\n--- Simple Calculator ---\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("5. Exit\n");
printf("Enter your choice: ");
}
int main() {
int choice, num1, num2;
float result;
while (1) {
display_menu();
scanf("%d", &choice);
// 退出条件
if (choice == 5) {
printf("Goodbye!\n");
break;
}
// 验证选择
if (choice < 1 || choice > 4) {
printf("Invalid choice. Try again.\n");
continue;
}
// 获取用户输入
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// 根据用户选择执行计算
switch (choice) {
case 1:
result = add(num1, num2);
printf("Result: %d + %d = %d\n", num1, num2, (int)result);
break;
case 2:
result = subtract(num1, num2);
printf("Result: %d - %d = %d\n", num1, num2, (int)result);
break;
case 3:
result = multiply(num1, num2);
printf("Result: %d * %d = %d\n", num1, num2, (int)result);
break;
case 4:
result = divide(num1, num2);
printf("Result: %d / %d = %.2f\n", num1, num2, result);
break;
}
}
return 0;
}
让我们分解关键概念:
- 使用了多种函数类型(返回值函数、无返回值函数)
- 函数执行特定的数学运算
display_menu()是一个无返回值函数,用于显示菜单- 算术函数返回计算结果
main()函数实现了一个菜单驱动的计算器- 包含除零错误处理
- 使用
switch语句选择操作
编译并运行程序:
gcc calculator.c -o calculator
./calculator
示例交互:
--- Simple Calculator ---
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice: 1
Enter two numbers: 10 5
Result: 10 + 5 = 15
--- Simple Calculator ---
...
Enter your choice: 5
Goodbye!
关于函数使用的关键点:
- 结合不同的函数类型
- 使用函数分解复杂问题
- 实现错误处理
- 创建模块化和可重用的代码
总结
在本实验中,你学习了如何在 C 编程中声明和定义函数、理解函数参数、从函数返回值、处理无返回值函数(void functions)以及练习函数的使用。你从创建一个简单的函数来问候用户开始,然后探索了具有多个参数和返回值的更复杂函数。你还学习了如何使用无返回值函数,并在程序中练习了函数的使用。这些基本概念对于在 C 语言中构建模块化和可重用的代码至关重要。



