1 什么是函数?
函数的比喻解释(魔法工具箱)
想象有一个神奇的"magicToolbox"工具箱,它可以完成特定任务。比如"drawStar"工具箱,按下按钮(调用函数)就能画出五角星。
生活中的函数例子(微波炉)
// 微波炉函数
Food heatFood(Food rawFood, int time) {
Food cookedFood;
// 加热过程...
return cookedFood;
}
使用示例:
Food myLunch = heatFood(frozenPizza, 2);
2 第一个函数程序
无参数函数示例
#include <iostream>
using namespace std;
// 定义打招呼函数
void greet() {
cout << "Hello, young programmer!" << endl;
cout << "This is my first function~" << endl;
}
int main() {
cout << "准备调用函数..." << endl;
// 调用函数
greet();
cout << "函数调用结束!" << endl;
return 0;
}
动手实验
- 修改greet()函数的输出内容
- 在main()中调用greet()三次
3 函数的组成部分
示例分析
// 计算平方的函数
int calculateSquare(int number) {
int result = number * number;
return result;
}
组成部分:
- 函数头:
int calculateSquare(int number)
- 返回类型:
int
- 函数名:
calculateSquare
- 参数列表:
(int number)
- 返回类型:
- 函数体:
{...}
内的代码 - return语句:返回计算结果
三明治制作函数分析
string makeSandwich(string bread, string filling) {
string sandwich = bread + filling + bread;
cout << "三明治做好了!" << endl;
return sandwich;
}
本章总结
概念 | 说明 | 示例 |
---|---|---|
函数定义 | 创建函数的完整代码 | void greet() {...} |
函数调用 | 执行函数功能 | greet(); |
返回类型 | 返回值的数据类型 | int , void |
参数 | 传入函数的数据 | (int number) |
函数体 | 函数执行的代码块 | {...} |
return | 返回结果并结束函数 | return result; |
课后练习:
- 创建singBirthdaySong()函数输出生日歌
- 编写calculatePerimeter()函数计算圆周长
- 观察家电思考对应的函数模型