Jump to content

Hi,

For college I have to write this program in C++:

 

 

Assignment 3 – Skript-Aufgabe 69 (4 points)

The number π can be defined through various infinite sums. Here are two of them.  

 

π / 4  = 1 – 1/3 + 1/5 – 1/7 ...

 

π / 2 = 1 + 1/3 + (1*2) / (3 * 5) + ( 1 * 2 * 3 ) / ( 3 * 5 * 7) + ...
Write a program for computing an approximation of π, based on these formulas. Which formula

is better for that purpose?

 

I have written this program here that outputs π using both methods, but it doesn't work.

 

 

#include <iostream>

int main()
{
    std::cout << "Number of cycles n=? ";
    unsigned int n;
    std::cin >> n;
    
    //Method 1
    double a = 0.0;
    unsigned int s = 1;
    while (s != (n+1))
        {
            if (s % 2 == 0)
                a += (1/(2*s - 1));
            else
                a -= (1/(2*s - 1));
            ++s;
        }
    a *= 4;
    std::cout << a << "\n";
    
    //Method 2
    a = 1;
    unsigned int t = 1;
    unsigned int b = 1;
    for (unsigned int x = 0; x != (n+1); ++x)
        {
            t *= x;
            b *= ( ( 2 * x ) + 1);
            a += ( t / b );
        }
    
    a *=2;

    std::cout << a << "\n";
    
    return 0;
}

Can any of you see the mistake? All help is appreciated.

 

PS. I'm coding in X-Code if that helps.



 

"Have you tried turning it off and on again?"

Link to comment
https://linustechtips.com/topic/232449-c-program-not-working-as-expected/
Share on other sites

Link to post
Share on other sites

What exactly doesn't working?
Any debugger? 

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to post
Share on other sites

You're doing integer divisions, making s a float or double would fix that.

Edit: Scratch that, it would make the modulus too annoying, just cast to a float before dividing.

Cheers.

"Have you tried turning it off and on again?"

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×