cpp通常按值传递参数,这意味着将数值参数传递给函数,而后者将其赋给一个新的变量。
double cube(double x)
double volume = cube(side) # side=5
被调用时,该函数将创建一个新的名为x的double变量,并将其初始化为5,这样,cube()执行的操作将不会影响main中的数据,因为cube使用的是side的副本,而不是原来的数据。用于接收传递的变量被称为形参。传递给函数的值被称为实参。cpp标准使用参数argument来表示实参,使用参量parameter来表示形参,因此参数传递将参数赋给参量。
在函数中声明的变量是该函数私有的,在函数被调用时,计算机将为这些变量分配内存,在函数结束时,计算机将释放这些变量使用的内存。这样的变量被称为局部变量,因为它们被限制在函数中。
1.多个参数
n_chars("R",25);
void n_chars(char,int);
2.example
// lotto.cpp -- probability of winning
#include <iostream>
// Note: some implementations require double instead of long double
long double probability(unsigned numbers, unsigned picks);
int main()
{
using namespace std;
double total, choices;
cout << "Enter the total number of choices on the game card and\n"
"the number of picks allowed:\n";
while ((cin >> total >> choices) && choices <= total)
{
cout << "You have one chance in ";
cout << probability(total, choices); // compute the odds
cout << " of winning.\n";
cout << "Next two numbers (q to quit): ";
}
cout << "bye\n";
// cin.get();
// cin.get();
return 0;
}
// the following function calculates the probability of picking picks
// numbers correctly from numbers choices
long double probability(unsigned numbers, unsigned picks)
{
long double result = 1.0; // here come some local variables
long double n;
unsigned p;
for (n = numbers, p = picks; p > 0; n--, p--)
result = result * n / p ;
return result;
}