为什么答案是5而不是6 [英] Why is the answer 5 and not 6

查看:88
本文介绍了为什么答案是5而不是6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int a = 5;

int a = a ++;

System.out.println(a);

答案是5而不是6.有人可以解释一下使用和更改操作员的逻辑



我尝试过:



i认为它是6但似乎是5

解决方案

假设重复的变量名称在你的问题中是一个拼写错误,解释在文档中:

增量/减量运算符可以在操作数之前(前缀)或之后(后缀)应用。代码结果++; ++结果; 将以结果增加1。唯一的区别是前缀版本( ++结果)评估为增量值,而后缀版本(结果++ )评估原始值。如果您只是执行简单的增量/减量,那么选择哪个版本并不重要。但是如果你在一个更大的表达式中使用这个运算符,你选择的那个可能会产生显着的差异。



  int  a =  5 ; 
int b = a ++; // a = 6,b = 5
int c = ++ a; // a = 7,c = 7


编译器在处理后缀增量时使用内部临时变量。如果你通过使用像编译器这样的附加变量扩展代码,你可以看到它发生的原因:

  int  a =  5 ; 
// int temp = a ++;
//
相同 int temp = a;
a = a + 1 ;
// 最后指定临时变量的值
a = temp;


int a=5;
int a=a++ ;
System.out.println(a);
the answer is 5 and not 6.can someone explain the logic of use and change operator

What I have tried:

i thought it was 6 but it seems to be 5

解决方案

Assuming the duplicated variable name is a typo in your question, the explanation is in the documentation:

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.


int a = 5;
int b = a++; // a = 6, b = 5
int c = ++a; // a = 7, c = 7


The compiler uses an internal temporary variable when processing the postfix increment. If you extend the code by using an additional variable like the compiler does you can see why it happens:

int a = 5;
// int temp = a++;
// is the same as
int temp = a;
a = a + 1;
// Finally the value of the temp variable is assigned
a = temp;


这篇关于为什么答案是5而不是6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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