what is wrong with my code ?

I want to Write a program that finds the summation of the following:
X = 1 – 1/2 +1/4 -1/6 + ……… -1/18 + 1/20


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 #include <iostream>
#include<conio.h>
using namespace std;

int main(){
  
	float y=0,i=0,z=0,x=1;
	cout<<x;
 for(int j=2;j<=20;j+=2)
 {
	
		if(j%4==0)
		{y=x/j;
		cout<<"+"<<y;
		y+=y;}
		else
		{i=-x/j;
		cout<<i;
		i-=i;}
		
 }
 z=1-i+y;
 cout<<"\nthe summation ="<<z;
	
	getch();
	return 0;
}

closed account (2LzbRXSz)
Not to sound ignorant, but wouldn't just doing
1
2
3
4
5
6
7
8
int main()
{
    
    float x = 1;
    
    cout << " The summation = " << x - 0.5 + 0.25 - 0.1666666666666667 - 0.0555555555555556 + 0.05 << endl;
    return 0;
}

achieve the same goal?
Last edited on
Lines 13 and 17. They discard what could have been accumulated.
i have to use the for lope to solve it .


keskiverto : so how i would write the code ?
At start the sum is 1.0.
On each iteration of the loop
1. Compute value of term
2. Add or deduct the term from the sum. (Could be sum += (cond) ? term : -term ;)
it worked , thank you .
Topic archived. No new replies allowed.