7.2函数参数和按值传递
C++通常按值传递参数,这意味着将数值参数传递给函数,而后者将其赋值给一个新的变量。
例如如下调用:
double volume = cube(side)
其中,side是一个变量,在前面的程序运行中,其值为5。cube()的函数头如下:
double cube (double x)
被调用时,该函数将创建一个新的名为x的double变量,并将其初始化为5。这样,cube()执行的操作将不会影响main()中的数据,因为cube()使用的是side的副本,而不是原来的数据。
用于接收值传递的变量称为形参。
传递给函数的值被称为实参。
出于简化的目的,C++标准使用参数(argument)来表示实参。
使用参量(parameter)来表示形参。
因此参数传递将参数赋给参量。
在函数中声明的变量(包括参数) 是该函数私有的。
在函数被调用时,计算机将为这些变量分配内存:在函数结束时,计算机将释放这些变量使用的内存。这样的变量称为局部变量,他们被限制在函数内部。这样的变量被称为,因为他们在程序执行过程中自动被分配和释放的。
7.2.1多个参数
函数可以有多个参数,在调用函数时,只需使用逗号将这些参数分开即可。
n_chars('R',25)
上述函数调用将两个参数传递给函数n_chars(),我们将稍后定义该函数。
同样,在定义函数时,也在函数头中使用由都喊分割的参数声明列表:
void n_chars(char c, int n);
该函数指出,函数n_chars()接收一个char参数一个int参数。传递给函数的值被赋值给参数c和n。
如果函数两个参数类型相同,则必须分别指定每个参数的类型,而不能像声明常规变量那样,将声明组合在一起:
void fifi(float a, float b)
void fufu (float a, b) //不被允许的
和其他函数一样,只需添加分号就可以得到该函数的原型:
void n_chars(char c , int n);
和一个参数情况一样,原型中的变量名不必与定义中的变量名相同,而且可以省略。
voie n_chars(char, int)
然后,提供变量名将使原型更容易理解,尤其是两个参数类型相同时,这样,变量名可以提醒参量和参数间的对应关系。
void melon_density(double weight , double volume);
程序清单7.3
#include <iostream>
using namespace std;
void n_chars(char ,int );
int main()
{
int times;
char ch;
cout<<"enter a character";
cin >> ch;
while(ch!='q')
{
cout << "enter a integer";
cin >> times;
n_chars(ch,times);
cout<< "/nenter another character or press the"
"q-key to quit:";
cin >> ch;
}
cout << "the value of time is" << time << ".\n";
return 0;
}
void n_chars(char c, int n )
{
while (n-- >0)
cout << c;
}
运行情况为:
enter a character:w
enter a integer: 50
wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
enter another character or press the q-key to quit:a
enter a integer: 20
aaaaaaaaaaaaaaaaaaaa
enter another character or press the q-key to quit:q
the value of time i 20
使用cin>>ch,而不是cin.get(ch)或是ch=cinj.get()来读取一个字符。这样做是有原因的。这两个cin.get()函数读取所有的输入字符,包括空格和换行符,而cin>>跳过空格和换行符。
当用户对程序提示作出相应时,必须在每行的最后按enter键,以生成换行符。
cin>>ch 方法可以轻松跳过这些换行符,单当输入的下一个字符为数字时,cin.get()将读取后面的换行符。
程序清单7.4
#include <iostream>
using namespace std;
long double probability(unsigned numbers, unsigned picks)
int main()
{
double toutal ,chices;
cout <<"enter the total number of choices on the game caed and\n"
" ghe number of picks allowed :\n";
while ((cin >> total >>choices) && choices <=total)
{
cout <<"you have once chance in ";
cout <<probability(total , choices);
cout <<"of winning .\n";
cout <<"next two number (q to quit):";
}
cout <<"bye \n";
return 0;
}
long double probability(unsigned numbers, unsigned picks)
{
long double resulet = 1.0;
long double n;
unsigned p;
for (n = number , p = picks ; p>0: n--,p--)
retult = resule *n / p;
return result;
}
运行结果如下:
enter the total number of choices on the game caed and
the number of picks allowed
49 6
you have once chance in 运算结果 of winning
next two number (q to quit):