当printvalues()调用参数6和7,printvalues参数x是创造和分配价值的6,和printvalues参数y是创造和分配价值7。
这将导致输出:
六
七
参数和返回值如何一起工作
通过使用两个参数和一个返回值,我们可以创建以数据为输入的函数,用它来做一些计算,并返回给调用方的值。
当函数()被调用,参数x赋值4,和Y参数指定的值为5。
()的函数进行x + y,这是价值的9,并返回该值返回功能main()。那么这9值发送到cout(由main())被打印在屏幕上。
输出:
这将导致输出:
六
七
参数和返回值如何一起工作
通过使用两个参数和一个返回值,我们可以创建以数据为输入的函数,用它来做一些计算,并返回给调用方的值。
这里是一个非常简单的函数的一个例子,该函数将两个数字相加,并将结果返回给调用方。
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//#include "stdafx.h" // Visual Studio users need to uncomment this line
#include <iostream>
// add() takes two integers as parameters, and returns the result of their sum
// The values of x and y are determined by the function that calls add()
int add(int x, int y)
{
return x + y;
}
// main takes no parameters
int main()
{
std::cout << add(4, 5) << std::endl; // Arguments 4 and 5 are passed to function add()
return 0;
}
当函数()被调用,参数x赋值4,和Y参数指定的值为5。
()的函数进行x + y,这是价值的9,并返回该值返回功能main()。那么这9值发送到cout(由main())被打印在屏幕上。
输出:
//#include "stdafx.h" // Visual Studio users need to uncomment this line
#include <iostream>
int add(int x, int y)
{
return x + y;
}
int multiply(int z, int w)
{
return z * w;
}
int main()
{
std::cout << add(4, 5) << std::endl; // within add(), x=4, y=5, so x+y=9
std::cout << multiply(2, 3) << std::endl; // within multiply(), z=2, w=3, so z*w=6
// We can pass the value of expressions
std::cout << add(1 + 2, 3 * 4) << std::endl; // within add(), x=3, y=12, so x+y=15
// We can pass the value of variables
int a = 5;
std::cout << add(a, a) << std::endl; // evaluates (5 + 5)
std::cout << add(1, multiply(2, 3)) << std::endl; // evaluates 1 + (2 * 3)
std::cout << add(1, add(2, 3)) << std::endl; // evaluates 1 + (2 + 3)
return 0;