英文:
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<(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)<(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<(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<(26-diff)?diff:(26-diff);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论