C++函数参数详解:值传递、多参数与局部变量
值传递的基本概念
C++默认使用按值传递(pass by value)的方式传递函数参数。这意味着当调用函数时,传递给函数的是实际参数的副本,而不是参数本身。
doublevolume=cube(side);// 调用函数,传递side的副本对应的函数定义:
doublecube(doublex)// x是新的局部变量,接收side的副本{returnx*x*x;}重要术语区分
- 实参(argument):调用函数时传递的实际值
- 形参(parameter):函数定义中声明的接收参数值的变量
- 参数传递:将实参赋值给形参的过程
值传递的关键特点
1. 数据保护
#include<iostream>usingnamespacestd;voidmodifyValue(intnum){num=100;// 修改的是副本,不影响原始数据cout<<"函数内: num = "<<num<<endl;}intmain(){intvalue=5;modifyValue(value);cout<<"主函数: value = "<<value<<endl;// 输出5,未改变return0;}2. 局部变量
函数内声明的变量(包括参数)都是局部变量:
- 函数调用时分配内存
- 函数结束时释放内存
- 与外部同名变量互不影响
多个参数的处理
函数定义
// 正确:每个参数单独声明类型voiddisplayChars(charch,intcount){for(inti=0;i<count;i++){cout<<ch;}}// 错误:不能合并声明voidwrongFunction(floata,b){// 编译错误!// ...}函数原型
// 方式1:带参数名(推荐,更清晰)voiddisplayChars(charch,intcount);// 方式2:不带参数名(允许,但不够清晰)voiddisplayChars(char,int);示例程序:显示指定次数字符
#include<iostream>usingnamespacestd;voidn_chars(char,int);intmain(){inttimes;charch;cout<<"Enter a character: ";cin>>ch;while(ch!='q'){cout<<"Enter an integer: ";cin>>times;n_chars(ch,times);cout<<"\nEnter another character or press the "<<"q-key to quit: ";cin>>ch;}cout<<"The value of times is "<<times<<".\n";cout<<"Bye\n";return0;}voidn_chars(charc,intn){while(n-->0)cout<<c;}运行结果:
Enter a character: W Enter an integer: 5 WWWWW Enter another character or press the q-key to quit: A Enter an integer: 3 AAA Enter another character or press the q-key to quit: q The value of times is 3. Bye**注意:**程序使用cin >> ch而不是cin.get(ch),是因为>>操作符会跳过空格和换行符,更适合这种交互场景。
实战示例:概率计算函数
下面是一个更实用的例子,计算从n个数中选择k个数的组合概率:
数学公式
从numbers个数中选取picks个数的组合数计算公式:
C(numbers, picks) = numbers! / (picks! × (numbers-picks)!)优化实现
为避免大数相乘导致溢出,采用交替乘除的策略:
#include<iostream>longdoubleprobability(unsignednumbers,unsignedpicks);intmain(){usingnamespacestd;doubletotal,choices;cout<<"Enter the total number of choices on the game card and\n"<<"the number of picks you want: \n";while((cin>>total>>choices)&&choices<=total){cout<<"You have one chance in ";cout<<probability(total,choices);cout<<" of winning.\n";cout<<"Next two numbers (q to quit): ";}cout<<"bye\n";return0;}longdoubleprobability(unsignednumbers,unsignedpicks){longdoubleresult=1.0;longdoublen;unsignedp;// 交替进行乘法和除法,防止中间结果过大for(n=numbers,p=picks;p>0;n--,p--)result=result*n/p;returnresult;}运行结果:
Enter the total number of choices on the game card and the number of picks you want: 49 6 You have one chance in 1.39838e+07 of winning. Next two numbers (q to quit): 51 6 You have one chance in 1.80095e+07 of winning. Next two numbers (q to quit): q bye总结要点
- 值传递是默认方式:传递的是参数的副本,保护原始数据不被意外修改
- 形参是局部变量:只在函数内部有效,与外部变量隔离
- 多参数需单独声明:即使类型相同,每个参数也要单独声明类型
- 函数原型可省略参数名:但为了可读性,建议保留
- 局部变量的生命周期:函数调用时创建,函数结束时销毁
- 数值计算要注意溢出:采用交替乘除等策略防止中间结果过大
理解函数参数传递机制是掌握C++函数编程的关键基础。值传递虽然安全,但在处理大型数据时可能效率较低,后续我们会介绍引用传递和指针传递来优化这种情况。