3.2 函数参数与返回值
1 带参数的函数
参数的概念
参数是函数的输入值,让函数可以处理不同的数据。就像数学函数 f(x) = x² 中的 x 就是参数。
比喻理解:想象一个果汁机:
- 参数:放入的水果(苹果、橙子等)
- 函数体:榨汁过程
- 返回值:榨好的果汁
计算平方的示例
#include <iostream>
using namespace std;// 带参数的函数
int calculateSquare(int num) {return num * num;
}int main() {int number = 5;// 调用时传入参数int result = calculateSquare(number); cout << number << "的平方是:" << result << endl;// 可以直接传入值cout << "3的平方是:" << calculateSquare(3) << endl;return 0;
}
趣味练习:动物叫声函数
void animalSound(string animal) {if(animal == "dog") {cout << "汪汪!" << endl;} else if(animal == "cat") {cout << "喵喵~" << endl;} else if(animal == "cow") {cout << "哞哞..." << endl;} else {cout << "我不知道这种动物的叫声" << endl;}
}int main() {animalSound("dog"); // 输出:汪汪!animalSound("bird"); // 输出:我不知道这种动物的叫声return 0;
}
扩展练习:添加更多动物的叫声,或者让函数返回叫声字符串而不是直接输出
2 返回值的函数
返回值类型
函数可以返回各种类型的值,就像数学函数的输出:
// 返回double类型
double calculateAverage(int a, int b) {return (a + b) / 2.0;
}// 返回bool类型
bool isEven(int num) {return num % 2 == 0;
}// 返回string类型
string getGrade(int score) {if(score >= 90) return "A";else if(score >= 80) return "B";else return "C";
}
多return语句的情况
函数中可以有多个return,但只会执行其中一个:
string checkNumber(int num) {if(num > 0) {return "正数";} else if(num < 0) {return "负数";}return "零";
}
void函数的特点
void函数不返回任何值,通常用于执行操作:
void printStars(int count) {for(int i = 0; i < count; i++) {cout << "* ";}cout << endl;
}int main() {printStars(5); // 输出:* * * * * return 0;
}
常见错误:尝试使用void函数的"返回值"
void func() { /*...*/ }
int main() {int x = func(); // 错误!void函数没有返回值
}
3 多参数函数
多个参数的传递
函数可以接收多个参数,用逗号分隔:
// 计算两个数的和
int addNumbers(int a, int b) {return a + b;
}// 打印个人信息
void printInfo(string name, int age) {cout << name << "今年" << age << "岁" << endl;
}
参数顺序的重要性
参数必须按照定义的顺序传递:
void introduce(string name, string hobby) {cout << "我是" << name << ",我喜欢" << hobby << endl;
}int main() {introduce("小明", "编程"); // 正确introduce("游泳", "小红"); // 逻辑错误!return 0;
}
实践练习:计算矩形面积
#include <iostream>
using namespace std;// 计算矩形面积的函数
double calculateRectangleArea(double length, double width) {return length * width;
}int main() {double l, w;cout << "请输入矩形的长和宽:";cin >> l >> w;double area = calculateRectangleArea(l, w);cout << "矩形面积是:" << area << endl;return 0;
}
扩展挑战:
- 添加计算矩形周长的函数
- 编写一个函数同时返回面积和周长
- 添加输入验证,确保长和宽都是正数
本章总结表
概念 | 说明 | 示例 |
---|---|---|
函数参数 | 函数的输入值 | void func(int param) |
返回值 | 函数的输出结果 | return value; |
void函数 | 不返回值的函数 | void print(...) |
多参数 | 多个输入值 | int add(int a, int b) |
参数顺序 | 传递参数的顺序必须匹配定义 | func(a,b) vs func(b,a) |
综合练习
- 编写
calculateCircleArea()
函数,接收半径返回圆面积 - 创建
isAdult()
函数,接收年龄返回是否成年(≥18岁) - 实现
printCard()
函数,接收姓名、年龄和爱好,打印个人信息卡片 - 挑战:编写
solveQuadratic()
函数,接收a,b,c参数,解一元二次方程
编程小项目:制作一个简单的学生成绩计算器,包含以下功能:
- 计算平均分(averageScore)
- 判断是否及格(isPassing)
- 输出成绩报告(printReport)