为什么声明变量的位置会改变它的行为方式? [英] Why does the place where you declare a variable change how it behaves?

查看:76
本文介绍了为什么声明变量的位置会改变它的行为方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下图所示,我正在运行一个关于dec_value值如何变化的小诊断。

如果我将dce_value与其余变量一起声明如图所示,如果我为第一个输入12 scanf,输出post while循环实际显示dec_value变为0.



As shown below, I am running a small diagnostic on how the value of dec_value changed.
If I declare dce_value together with the rest of my variables as shown, if i input 12 for the first scanf, the output post while-loop actually shows that dec_value changed to 0.

 int dec_value, bin_value, i[15], j=0, quo, rem;
//int dec_value;

 printf("Please enter the decimal number: ");
 scanf("%d", &dec_value);

 quo = dec_value;

 printf("%d \n", dec_value);

 while(j < 16)
 {
     i[j] = quo % 2;
     quo = quo / 2;
     j++;
 }

 printf("%d \n", dec_value);





我的尝试:



解决问题的唯一方法是,如果我在单独的行上声明dec_value,或者如果..

i [j] = quo%2;

被取消了。我很困惑为什么会发生这种情况。



What I have tried:

The only way I got around the problem is if i declared dec_value on a separate line, or if..
i[j] = quo % 2;
was nulled. And I am very puzzled as to why this is happening.

推荐答案

你应该学会尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。



调试器允许你跟踪执行逐行检查变量,你会看到有一点它会停止你所期望的。

在Visual Studio 2010中掌握调试 - 初学者指南 [ ^ ]

http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html [ ^ ]

https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html [ ^ ]



在你的情况下,没有区别,两个声明完全相同。

使用调试器查看代码正在做什么。

你的程序有一个错误:

我是一个大小为15的数组,从 i [0] 我[ 14]

但你的progran在 i [15] 中写入了另一个变量,哪个是编译器相关的。
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

In your case, there is no difference, both declaration are exactly the same.
Use the debugger to see what the code is doing.
Your program have a bug:
I is an array of size 15 which is from i[0] to i[14]
but your progran write in i[15] which write in another variable, which one is compiler dependent.


没有区别(除非你有一个错误的编译器)。

无论如何,我总是会检查 scanf 返回值(在您的方案中应该 1 )。
It makes no difference (unless you have a buggy compiler).
In any case, I would always check the scanf return value (it should be 1, in your scenario).


这篇关于为什么声明变量的位置会改变它的行为方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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