0
Why this answer is unsensable for me?
public static int answer(int a,int b){ int c=a; for(c=a;c<b;c++){ c+=c; } return c; } p s v m(string [] ghr){ System.out.println(answer(2,6)); } answer is 11 rather than 16 which is unsensable or may be I m missing some fact plz explain someone to me.how this's happening? thank you.
3 Respostas
0
16 is insensible for me BTW.
11 is right answer explained by Udi Finkelstein.
+ 3
I don't know what was your intention, but if answer(a, b) should sum the numbers between a and b-1 (inclusive) then your bug is that you use c for both the loop counter and the sum.
It starts with 2 then you double it by "c += c" to 4. The loop increments it to 5. It is doubled again to 10,and incremented to 11,at which point the loop the bounds check (c<b) fails, and you get your final result.
public static int answer(int a,int b){
int c, sum=0;
for(c=a;c<b;c++){
sum+=c;
}
return sum;
}
+ 2
thanks guys I thought the value or c is changing and hence when c gets a new value in a loop then it's changes
like
c+=c;
c=2+2;
now c=4;
c=4+3;
now c=7;
c=7+4;
and so on...
I was thinking like this..😉