Click here to Skip to main content
15,892,072 members

Recurrence in C++ exercise

Member 12401659 asked:

Open original thread
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

C++
#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 ) ) // to make condition where the number become negative
            {
                sign = -1;
    
    
            }
            if ( ( i % 4 != 0 ) && ( i > 1 ) )  // to make condition where the number become positive
            {
                sign = 1;
                cout << " + ";
            }
            if ( i == 1 ) // to prevent 1st number not show " + " symbol
            {
                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
Tags: C++

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900