main函数,一个程序有且只有一个main函数,main函数是程序的入口。
函数定义:
类型 函数名(类型1 形参变量1,类型2 形参变量2 ... 类型n 形参变量n){
声明部分
执行语句部分
}
#include<iostream>
#include<ctime>
using namespace std;
//计算两个浮点数的最大值
float max(float a,float b){
float z;
z = a>b?a:b;
return z;
}
//showTime函数
void showTime(){
long lct;
lct = time(0);
cout<<lct<<endl;
}
int main(){
float x = 0.99,y=0.88,c;
showTime();
c = max(x,y);
cout<<"max="<<c<<endl;
return 0;
}
函数调用和声明
函数的声明:类型 函数名(类型1 形参变量1,类型2 形参变量2 ... 类型n 形参变量n)
函数调用:函数名(实际参数)
形式参数和实际参数
形参是函数定义时候的参数。
实参是函数调用时的参数。
#include<iostream>
using namespace std;
int main(){
int a =3 ,b = 4;
//函数声明
void swap(int a1,int a2);
//函数调用
swap(a,b);
cout<<"a="<<a<<"b="<<b<<endl;
return 0;
}
//定义函数
void swap(int a1,int b1){
int c;
c = a1;
a1 = b1;
b1 = c;
}
函数返回值
return 表达式
return 0;
函数重载
函数名相同,返回的类型和参数的类型不同。
函数默认参数
void mal(int a,int b=3,int c =5){...}
函数递归调用
函数的递归调用是一个不断调用自己的过程。
//用递归调用求n!
#include <iostream>
using namespace std;
int main(){
int a =3;
int result;
int fact(int n);
result = fact(a);
cout<<"阶乘为:"<<result<<endl;
}
int fact(int n){
int f1;
if(n==1){
f1 = 1;
}
else{
f1 = n*fact(n-1);
}
return f1;
}