I am still learn about algorithms, i have a homework. I must make an output
Sum of : 1/2 + 1/4 + 1/6 - 1/8 + 1/10 + 1/12
Result : 0.975
But output of my program
Sum of : 1/2 + 1/4 + 1/6-1/8 + 1/10 + 1/12
Result : 0.975
I dont know how to make space `negative sign`, if i use cout there will show twice negative sign.
my program
#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
int i ,sign, p, q, n;
double x , S;
S=0;
cout << "Sum of :";
for (i=1; i <= 6; i++)
{
if ( (i % 4 == 0) && ( i > 1 ) ) {
sign = -1;
}
if ( ( i % 4 != 0 ) && ( i > 1 ) ) {
sign = 1;
cout << " + ";
}
if ( i == 1 ) {
sign =1;
}
p = sign*1;
q = ( 2 * ( i - 1 ) ) + 2;
cout << p << "/" << q;
x = ( 1.0 * p / q );
S = S + x;
}
cout << "\n" << S;
}
I realize my program too many operation that not needed, could u help me make it more effecient ?
What I have tried:
Output of my program
Sum of : 1/2 + 1/4 + 1/6-1/8 + 1/10 + 1/12
Result : 0.975