开发者

Incorrect sum - For loop in C

I am trying to sum values in a for loop with C. The initial value of variable x = 1 and I want to double it a set number of times and add the result. I have made the for loop, but my sum is always off by the initial value.

For example, if x = 1, the pattern should go:

1, 2, 4, 8, 16

...and the total should be 31. Unfortunately, total is off by one.

int x = 1;
int y = 10;
int total;

for(int i = 1; i < y; i++)
{   
   x *= 2;
   total += x;
}

printf("Total: %开发者_如何转开发d\n", total);

This is off by one. How can I have the loop start with 1 instead of 2?


Switch the two statements in the body of the for loop. Also it is a good idea to initialize total to 0, in case you want to move all of this into a function.


As is usually the case with erroneous code, there is more that one way to "fix" it. While you made it sufficiently clear as to what you are trying to implement, nobody knows how you are trying to implement it.

  • As @Ray Toal already noted in his answer, the correct result can be obtained by initializing total to 0 before the cycle and doing x *= 2 after the addition inside the cycle.

  • Alternatively, one can say that the cycle is OK as it is in the original code. You just have to initialize the total to 1 before the cycle.

Which approach is closer to what you were trying to implement originally - only you know. In both cases make sure you make the correct number of iterations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜