为什么在使用"for"循环时在程序中两次添加"int"标记时输出会有所不同? [英] Why the output is different when we add 'int' tag twice in a program when using 'for' loop?
问题描述
我是一名学习者,是C语言的新手.当我创建一个使用for循环提供两个数字的幂的函数时,我在循环开始之前遇到int声明,并且在循环中更改了程序的输出.为什么会这样?
I am a learner and new to C language. While I was creating a function which will give power of two numbers using for loop I encounter that using int declaration before loop starts and also in the loop changes the output of my program. Why is this so?
使用'int'声明一次并带有正确输出的代码;
Code using 'int' declaration once with correct output;
# include<stdio.h>
int main()
{
int x, y;
int r = 1;
int k;
printf("Enter base number:");
scanf("%d", &x);
printf("Enter power");
scanf("%d", &y);
for (k = 1; k <= y; k++)
{
r = r * x;
}
printf("Power is %d", r);
return 0;
}
正确的输出:
Enter base number:7
Enter power3
Power is 343
错误代码2:
# include<stdio.h>
int main()
{
int x, y;
int r = 1;
int k;
printf("Enter base number:");
scanf("%d", &x);
printf("Enter power");
scanf("%d", &y);
for (k = 1; k <= y; k++)
{
int r = r * x;
}
printf("Power is %d", r);
return 0;
}
错误的输出:
Enter base number:7
Enter power3
Power is 1
你能告诉我为什么吗?
推荐答案
for (k = 1; k <= y; k++)
{
int r = r * x;
}
在for
循环内部的
int r
声明了一个单独且唯一的变量,该变量仅在for
循环的范围内可见.
int r
inside of the for
loop declares a separate and unique variable which only is visible in the scope of the for
loop.
此r
不在for
循环之外引用r
.
但是在循环(内部)r
的初始化部分内部,内部r
不会遮蔽外部r
,因为内部r
的声明在此时不满足时间.
But inside of the initialization part of the loop's (inner) r
, the inner r
doesn't shadow the outer r
because the declaration of the inner r
isn't fulfilled at this moment of time.
因此,r * x
中的r
是指外部r
,而不是内部r
.
So, the r
in r * x
refers to the outer r
, not the inner one.
您写过吗:
for (k = 1; k <= y; k++)
{
int r = 2;
r = r * x;
}
然后所有r
都将引用内部的r
,并且完全遮蔽外部的r
.
then all r
's would refer to the inner r
and would completely shadow the outer one.
此后,当您使用
printf("Power is %d", r);
它输出外部r
变量的值,该值保持不变.
it prints the value for the outer r
variable, which remains unchanged. This is proven with the output of
Power is 1
旁注:
Side Note:
- 在每次迭代中声明要声明一个新变量时,在循环体内声明变量实际上没有多大意义.编译器可以将其优化为仅一个定义,但最好将声明放置在
for
循环的初始化部分内,或者在循环之前进行声明.
- It doesn't really much sense to declare variables inside of loop's body as you instruct to declare a new variable at each iteration. A compiler can optimize this to only one definition, but better place declarations inside of the initialization part of the
for
loop or declare them before the loop.
这篇关于为什么在使用"for"循环时在程序中两次添加"int"标记时输出会有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!