Java Program to C++?

So I'm trying to change this Java program to C++ but have the same result, and compilers haven't been working correctly for me...

Estimate p) p can be computed using the following series:
m(i) = 4(1 - 1 / 3 + 1 / 5 - 1 / 7 + 1 / 9 - 1 / 11 + ... + (((-1)^i + 1) / 2i - 1)))
Write a method that returns m(i) for a given i and write a test program that displays
the following table:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Exercise_06_14 {
	/** Main Method */
	public static void main(String[] args) {
		// Display table
		double start = 1;			// Start series
		double end   = 901;		// End series
		System.out.println("\ni           m(i)     ");
		System.out.println("---------------------");
		for (double i = start; i <= end; i += 100) {
			System.out.printf("%-12.0f", i);
			System.out.printf("%-6.4f\n", estimatePI(i));
		}
	}

	/** Method estimatePI */
	public static double estimatePI(double n) {
		double pi = 0;		// Set pi to 0
		for (double i = 1; i <= n; i ++) {
			pi += Math.pow(-1, i +1) / (2 * i - 1);
		}
		pi *= 4;
		return pi;
	}
}
So where is your C++ attempt?

Just rip out all the public static, change the main signature and fix the System.out.println() and you're almost done.

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
28
29
30
31
32
#include <iostream>
#include <iomanip>

static double estimatePI( int n ) {

    double piby4 = 0 ;

    // m(i) = 4(1 - 1 / 3 + 1 / 5 - 1 / 7 + 1 / 9 - 1 / 11 + ... + (((-1)^i + 1) / 2i - 1)))
    double num = 1 ;
    double denom = 1 ;

    for( int i = 0 ; i < n ; ++i ) {

        piby4 += num / denom ;
        num = -num ; // alternating +1 -1
        denom += 2 ; // 1, 3, 5, 7 etc.
    }

    return piby4 * 4 ;
}

int main() {

    const int start = 1 ;
    const int end = 901 ;

    std::cout << "\n   i    m(i)     \n-------------\n"
              << std::fixed << std::setprecision(4) ; // 4 digits after the decimal point

    for( int i = start; i <= end; i += 100 )
        std::cout << std::setw(5) << i << std::setw(8) << estimatePI(i) << '\n' ;
}

http://coliru.stacked-crooked.com/a/8646639ff3fd6093
I'm trying to change this Java program to C++ but have the same result.

wait you want C++ program to have different result?

compilers haven't been working correctly for me

please share compiler output errors, and the code which produces these errors.
It's barely worth the effort.

Just some wannabe with "found code" who
a) stumbled on some code to compute PI, but it was written in Java and
b) stumbled into a C++ forum with said code and some bleating to convert it to C++.

Hence the reason I'm in the beginner forums...
Topic archived. No new replies allowed.