函数是一段独立的代码块,用于执行特定的任务。在C++中,函数可以接受参数和返回值。
void printHello() {
cout << "Hello, World!" << endl;
}
int main() {
printHello();
return 0;
}
void printMessage(string message) {
cout << message << endl;
}
int main() {
printMessage("Hello, World!");
return 0;
}
void printMessage(string message, int times = 1) {
for (int i = 0; i < times; i++) {
cout << message << endl;
}
}
int main() {
printMessage("Hello, World!");
printMessage("Hi there!", 3);
return 0;
}
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swap(x, y);
cout << "x = " << x << ", y = " << y << endl;
return 0;
}
void add(int a, int b) {
int sum = a + b;
cout << "Sum: " << sum << endl;
}
int main() {
add(5, 3);
return 0;
}
int multiply(int a, int b) {
return a * b;
}
int main() {
int result = multiply(5, 3);
cout << "Result: " << result << endl;
return 0;
}
void calculate(int a, int b, int &sum, int &difference, int &product) {
sum = a + b;
difference = a - b;
product = a * b;
}
int main() {
int x = 5, y = 3, sum, difference, product;
calculate(x, y, sum, difference, product);
cout << "Sum: " << sum << ", Difference: " << difference << ", Product: " << product << endl;
return 0;
}
通过函数参数和返回值,我们可以实现模块化编程,将复杂的任务分解成多个独立的函数,提高代码的可读性和可维护性。在编写函数时,要注意参数的类型和数量,以及返回值的类型和用途,确保函数可以正确地完成任务并与其他部分协调工作。