在使用Java中的三元运算符进行值相加时出现错误值。

huangapple go评论57阅读模式
英文:

wrong value coming when adding values using ternary operator in java

问题

sum的值在for循环中即使我在其中添加也不会改变。diff的值是3。

打印出的值在初始迭代中是3 3 3,但应该是3 6 9。有人可以帮忙吗?

     循环开始           
     sum = sum + diff<(26-diff)?diff:(26-diff);
     循环结束
英文:

The value of sum is not changing even if I am adding it inside the for loop. Value of diff is 3

The value which is getting printed is like 3 3 3 in initial iteration which should be 3 6 9.
Can someone please help?

     loop start           
     sum = sum + diff&lt;(26-diff)?diff:(26-diff);
     loop end

答案1

得分: 2

数字表达式计算的优先顺序是导致你得到错误结果的原因。你当前的语句等同于这个:

sum = (sum + diff) < (26 - diff) ? diff : (26 - diff);

因此等同于 diff 的值,它始终是 3。将你的语句修改为这样:

sum = sum + (diff < (26 - diff) ? diff : (26 - diff));

你将会得到你期望的行为。你也可以使用 += 运算符来修复这个问题,将你的语句修改为:

sum += diff < (26 - diff) ? diff : (26 - diff);
英文:

Order of precedence in how your numeric expression is being calculated is what's causing you to get the wrong result. Your current statement is equivalent to this:

sum = (sum + diff)&lt;(26-diff)?diff:(26-diff);

and so equates to the value of diff, which is always 3. Change your statement to this:

sum = sum + (diff&lt;(26-diff)?diff:(26-diff));

and you'll get the behavior you're expecting. you can also use the += operator to fix this by changing your statement to:

sum += diff&lt;(26-diff)?diff:(26-diff);

huangapple
  • 本文由 发表于 2020年10月11日 22:19:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/64305044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定