Reputation: 77
I'm supposed to make a program which allows me to do this calculation: -5+10-20+40-80+160
I've done this so far:
const int START = -5, LIMIT = 160;
int somme = 0;
int terme = START;
do {
somme += terme;
terme = terme * 2;
terme = -terme;
} while(terme <= LIMIT);
printf ("equals %d\n\n", somme);
But when I run it it shows -215 and of course it's not the correct answer. I'd really appreciate your help.
Upvotes: 0
Views: 108
Reputation: 5373
For a calculation like this, you should look at the expression more carefully. What you want is:
-5+10-20+40-80+160
= 5*(- 1 + 2 - 4 + 8 - 16 + 32)
= 5*( (-1)^1*(2^0) + (-1)^1*(2^1) + (-1)^1*(2^2) + (-1)^1*(2^3) + (-1)^1*(2^4) + (-1)^1*(2^5) )
where in C terms, a^b is equivalent to pow(a,b)
= 5 * sum over i ((-1)^(i+1) * 2^i ) where i goes from 0 to 5
Do you think that it would be easier to iterate over a variable i
in a for
loop? Ill leave this as an exercise.
Upvotes: 1
Reputation: 67
another cool way:
const int START = -5, LIMIT = 160;
int somme = 0;
for(int terme = START; (terme<LIMIT && (-terme)<LIMIT)||(printf("equals //
%d\n\n",somme),0); terme = -(terme*2)){
somme += terme;
}
Upvotes: 0
Reputation: 6407
You should use absulute value of terme
in condition of your loop, that better have to be PRE-CONDITION while:
#include <stdio.h>
#define ABS(X) (X>=0)?(X):(-X)
int main()
{
const int START = -5, LIMIT = 160;
int somme = 0;
int terme = START;
while( ABS(terme) <= LIMIT )
{
somme += terme;
terme = terme * 2;
terme = -terme;
}
printf ("equals %d\n\n", somme);
}
Upvotes: 1