简体   繁体   English

C++ - 使用特定函数计算 x 和 y 的最终值

[英]C++ - Calculating final values of x and y with a specific function

I really do not have any clue about how to solve this task, can someone please help?我真的不知道如何解决这个任务,有人可以帮忙吗?

Consider the following function definition:考虑以下函数定义:

void f(int i, int &j) {
    j = i+1;
    i = j*2;
    j += i; 
}

In the following code:在以下代码中:

int x = 4, y = 7;
f(x, y);

What are the final values of x and y ? xy的最终值是多少?

For starters you could just run the code... but otherwise we can try and predict the output.对于初学者,您可以只运行代码……但否则我们可以尝试预测输出。

For starters the function f has two parameters, i and j.首先,函数 f 有两个参数 i 和 j。 The & Infront of the j means that the value of the function input is passed by reference (the value of the variable will be edited). j前面的&表示函数输入的值是通过引用传递的(变量的值会被编辑)。

So now let's evaluate the function with inputs 4, 7. We get:所以现在让我们用输入 4、7 来评估函数。 我们得到:

j = 4+1 = 5
i = 10
j += i, j = 15

Because the variable y was passed by reference, its value will become 15. The variable x was passed by value, so it doesn't get affected and thus stays as 4.因为变量 y 是通过引用传递的,所以它的值将变为 15。变量 x 是通过值传递的,所以它不会受到影响,因此保持为 4。

Simply just run the code.Anyway the output will be只需运行代码。无论如何,输出将是

x=4(because it is passed as pass by value ->any change will not affect the outside the function f) y=15(because it is passed as pass by reference->any change will affect the outside the function f) x=4(因为是按值传递->任何变化都不会影响函数f外部) y=15(因为它是按引用传递->任何变化都会影响函数f外部)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM