Reputation: 21
I have a homework to make an algorithms for sum this sequence : S = 1 - 1/2 + 1/4 - 1/6 + 1/8 - 1/10 + ... + 1/2n
if the user input 2 the sum will be 1 - 1/2 = 1/2
and etc.
Here is my coding :
int main() {
int num, N, k;
double S;
cout << "enter the sequence : ";
cin >> N;
for (num = 1, k = 0, S = 1; num <=N; num++) {
num++;
k=+2;
if (num % 2 == 0) {
S -= 1/k;
} else {
S += 1/k;
}
}
cout << "The sum is " << S;
system("PAUSE");
return 0;
}
I'm so confused why the sum always refer to 1 ?? Can anyone explain to me why this happen??
Upvotes: 2
Views: 1122
Reputation:
for(num = 1, sum = 1; num <=N; num++){
if(num%2==0){
sum += 1/(num*2);
}else{
sum -= 1/(num*2);
}
}
That should do it, provided the nth term in your sequence is (1/((n-1)*2))
.
EDIT: As pointed out below, when performing division, one of the operands needs to be non integer to prevent the result from being an integer. The correction to my attempt above would be:
for(num = 1, sum = 1; num <=N; num++){
if(num%2==0){
sum += 1.0/(num*2);
}else{
sum -= 1.0/(num*2);
}
}
Upvotes: 1
Reputation: 21351
In your loop you have this
k=+2;
so you assign the value 2 to k
every iteration. You probably want
k+=2;
also take heed of the integer division problem highlighted in the other answer
Upvotes: 3
Reputation: 143209
Try 1./k
— otherwise integer division of 1 by anything will yield zero. (and see the other answer about =+
vs +=
typo).
Upvotes: 7