为什么在使用"for"循环时在程序中两次添加"int"标记时输出会有所不同? [英] Why the output is different when we add 'int' tag twice in a program when using 'for' loop?

查看:91
本文介绍了为什么在使用"for"循环时在程序中两次添加"int"标记时输出会有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名学习者,是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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆