[英]Pass to Value in C math
I am just learning C. i am working through this problem trying to predict the output: 我只是在学习C.我正在解决这个问题,试图预测输出:
#include <stdio.h>
int gNumber;
int MultiplyIt( int myVar );
int main (int argc, const char * argv[])
{
int i; gNumber = 2;
for ( i = 1; i <= 2; i++ )
gNumber *= MultiplyIt( gNumber );
printf( "Final value is %d.\n", gNumber );
return 0;
}
int MultiplyIt( int myVar )
{
return( myVar * gNumber );
}
so if you run this, the output is 512. i am a bit confused on how the calculation is getting from the initial value of 2, then first time through the 'for' loop it then assigns gNumber = 8. then jumps to 512... 因此,如果你运行它,输出是512.我对计算从初始值2得到的方式有点困惑,然后第一次通过'for'循环然后分配gNumber = 8.然后跳转到512。 ..
maybe i am missing something easy here, but as i said, i am very new to C and programing in general.. 也许我在这里错过了一些简单的东西,但正如我所说的,我对C很新,并且编程一般。
Let's start from here: 让我们从这里开始:
gNumber *= MultiplyIt( gNumber );
This line contains a call to MultiplyIt
with myVar = gNumber
. 该行包含对MultiplyIt
的调用myVar = gNumber
。 By looking at the return value of that function, we can say that MultiplyIt( gNumber )
is equivalent to gNumber * gNumber
. 通过查看该函数的返回值,我们可以说MultiplyIt( gNumber )
等于gNumber * gNumber
。 So the line above is equivalent to this: 所以上面的行等同于:
gNumber *= gNumber * gNumber;
or also: 或者:
gNumber = gNumber * gNumber * gNumber;
In plain words, the body of the for
-loop replaces gNumber
with its cube. 简单来说, for
-loop的gNumber
用它的立方体替换gNumber
。
The loop runs two times, with i
going from 0 to 1 (inclusive). 循环运行两次,与i
打算从0到1(含)。 gNumber
is 2 initially. gNumber
最初为2。 Putting everything together, here's what the loop is doing: 将所有内容放在一起,这是循环正在做的事情:
gNumber = 2 * 2 * 2 = 8; /* First iteration, i = 1 */
gNumber = 8 * 8 * 8 = 512; /* Second iteration, i = 2 */
given the following instrumented code: 给出以下检测代码:
#include <stdio.h>
int gNumber;
int MultiplyIt( int myVar );
int main ( void )
{
int i;
gNumber = 2;
for ( i = 1; i <= 2; i++ )
{
gNumber *= MultiplyIt( gNumber );
printf( "\n%s, gNumber *= MultiplyIt(): %d\n", __func__, gNumber);
}
printf( "Final value is %d.\n", gNumber );
return 0;
}
int MultiplyIt( int myVar )
{
printf( "\n%s, pasted parameter: %d\n", __func__, myVar);
printf( "%s, global gNumber: %d\n", __func__, gNumber);
return( myVar * gNumber );
}
the output is: 输出是:
MultiplyIt, pasted parameter: 2
MultiplyIt, global gNumber: 2
main, gNumber *= MultiplyIt(): 8
MultiplyIt, pasted parameter: 8
MultiplyIt, global gNumber: 8
main, gNumber *= MultiplyIt(): 512
Final value is 512.
so the first pass through the for
loop is: 所以第一次通过for
循环是:
2*2*2 = 8
the second pass through the for
loop is: 第二次通过for
循环是:
8*8*8 = 512
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.