函数的定义:(其实是可以参考main函数怎么写的)
#include <iostream>
using namespace std;
/*
返回值类型 函数名 (参数列表)
{
函数体语句
return表达式
}
*/
int add(int num1, int num2)
{
int sum = num1 + num2;
return sum;
}
int main()
{
return 0;
函数的调用:
#include <iostream>
using namespace std;
int add(int num1, int num2)//形参
{
int sum = num1 + num2;
return sum;
}
int main()
{
int a = 10; int b = 20;
int c = add(a, b);实参
cout << "c=" << c << endl;
cout << add(20, 50) << endl;
return 0;
函数的值传递:(交换)
#include <iostream>
using namespace std;
void swap (int num1,int num2)//若函数不需要返回值,则可以在前面加一个void
{
cout << "第一个数字:" << num1 << endl;
cout << "第二个数字:" << num2 << endl;
int temp = num1;
num1 = num2;
num2 = temp;
cout << "交换位置后的情况:" << endl;
cout << "第一个数字:" << num1 << endl;
cout << "第二个数字:" << num2 << endl;
}
int main()
{
int a = 0; int b = 0;
cout << "a=" << endl;
cin >> a;
cout << "b=" << endl;
cin >> b;
swap(a, b);
return 0;
}
常见的函数样式
#include <iostream>
using namespace std;
//1.无参无返
void test1()
{
cout << "this is a test1" << endl;
}
//2.有参无返
void test2(int a)
{
cout << "this is a test2" << endl;
cout << "a=" << a << endl;
}
//3.无参有返
int test3()
{
cout << "this is a test3" << endl;
return 886;
}
//4.有参有返
int test4(int a)
{
cout << "this is a test4" << endl;
return a;
}
int main()
{
//1.无参无返调用
test1();
//2.有参无返调用
test2(8);
//3.无参有返调用
int num1 = test3();
cout << "返回值为:" << num1 << endl;
//4.有参有返调用
int num2 = test4(10);
cout << "返回值为:" << num2 << endl;
system("pause");
return 0;
}
函数的声明:
#include <iostream>
using namespace std;
int bigger(int a, int b);//函数的声明,可以有很多次
int main()
{
int a = 0; int b = 0;
cout << "输入第一个数字:" << endl;
cin >> a;
cout << "输入第二个数字:" << endl;
cin >> b;
int x = bigger(a, b);
cout << "其中比较大的是:" << x << endl;
system("pause");
return 0;
}
int bigger(int a, int b)//函数的定义,只能有一次
{
if (a > b)
{
return a;
} //可以用三目运算符超级简单完成此次动作
else // retuen a>b?a:b;
{
return b;
}
}
函数的分文件编写(三部分:第一.h的头文件。第二.cpp的函数文件。第三.cpp的main函数文件)
第一部分(记得是头文件而且是.h文件)
#include <iostream>
using namespace std;
void swap(int a, int b);//函数的声明
第二部分(在源文件创建的函数文件)
#include"swap.h"//关联到头文件
void swap(int a, int b)
{
int num = a;
a = b;
b = num;
cout << "a=" << a << endl;
cout << "b=" << b << endl;
}
第三部分(在源文件创建的main函数文件)
#include "swap.h"//关联到头文件
int main()
{
int a = 0; int b = 0;
cout << "输入a=" << endl;
cin >> a;
cout << "输入b=" << endl;
cin >> b;
swap(a, b);
system("pause");
return 0;
}