1.形式参数:相当于局部变量 类型标识符+函数名+(形参){语句序列}
2.函数调用就是用实参初始化形参 函数名(实参) 嵌套调用:函数体内调用另一个函数 F5:执行程序
- 模拟生成随机数
函数原型:int rand(void)
头文件:<cstdlib>
原型:void srand(unsigned int seed):为使rand()产生一序列随机整数二设置起始点.使用1作为seed参数,可以重新初始化rand(),不同的种子会产生不同的随机数序列。
参数:seed产生随机数的种子
所需头文件:<cstdlib>
-主函数
#include <iostream>
#include <cstdlib>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define endl '\n'
using namespace std;
enum GameStatus{win,lose,playing};
//投色子、计算和、输出和
int rollDice(){
int die1 = 1 + rand()%6;
int die2 = 1 + rand()%6;
int sum = die1 + die2;
cout<<"player rolled"<<die1<<"+"<<die2<<"="<<sum<<endl;
return sum;
}
int main(){
int sum,mypoint;
GameStatus status;
unsigned seed;
int rollDice();
int i;
for(i = 1;i < 7;i++){
cout<<i<<endl; //输出i值,
}
cout<<"请输入一个未符号的整数";
cin>>seed;//输入随机数种子
srand(seed);//将种子传递给rand()
sum = rollDice();//第一轮投色子、计算和数
switch(sum){
case 7: //如果和数为7或10,win
case 11:
status = win;
break;
case 2:
case 3:
case 12:
status = lose;
break;
default:
status = playing;
mypoint = sum;
cout<<"point is"<<mypoint<<endl;
break;
}
while(status == playing){//只要状态为playing,继续
sum = rollDice();
if(sum == mypoint) //某轮的和数等于点数则取胜
status = win;
else if (sum == 7)
status = lose;
}
//当状态不为playing时循环结束,输出游戏结果
if(status == win)
cout<<"player wins"<<endl;
else
cout<<"player lose"<<endl;
return 0;
}
嵌套调用
fun1函数内嵌套fun2函数,最终返回。
递归调用
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
#define endl '\n'
using namespace std;
unsigned fac(unsigned n){
unsigned f;
if (n == 0)
f = 1;
else
f = fac(n-1)+1;
return f;
}
int main(){
int Out;
Out = fac(100);
cout<<Out<<endl;
}
- 递归,汉诺塔
#include <iostream>
using namespace std;
//把src针的最上面一个盘子移动到dest针上
void move(char src, char dest){
cout<<src<<"-->"<<dest<<endl;
}
//把n个盘子从src针移动到dest针,以medium针作为中介
void hanoi(int n, char src, char medium, char dest){
if (n == 1)
move(src,dest);
else{
hanoi(n-1,src,dest,medium);
move(src,dest);
hanoi(n-1,medium,src,dest);
}
int main(){
int m;
cout<<"输入盘子个数";
cin>>m;
hanoi(m,'A','B','C');
return 0;
}
}
函数参数传递
实参类型与形参类型必须相同
参数双向传递:<传引用>
- 引用类型
引用(&)是标识符的别名
例如:
int i,j;
int &ri = i;//定义int引用ri,并初始化为变量i的引用
现在ri = j;相当于i = j;
- 函数参数的传递
#include <iostream>
using namespace std;
void swap(int &a,int &b){
int t = a;
a = b;
b = t;
}
int main(){
int a = 12,b = 13;
swap(a,b);
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
return 0;
}
*问题:可以定义指向引用的指针.(错)
解析:
引用不是对象,引用并没有在程序中占据内存空间,故没有地址的说法.
- 可变长度的形参表,不定义参数数量的函数
initializer_list <int> li;