Master dev C++ please come!

I hve a problem,
There is the question
1/1^2 - 1/2^2 + 1/3^2 -1/4^2 + ...
the formulla is given limit varible < 0.000001 can be ignored
please search the total

I already make the program
Please see whether this is correct or not? Do you have any better code? Please tell me the most simple program :D


#include <iostream>
#include <math.h>
using namespace std;
main()
{
int n=1;
const double variable=0.000001;
double satuan,total=0;

while(satuan > variable)
{
n++;
satuan = -1/(pow(n,2)*pow(-1,n));
total += satuan;
}
cout<<"The total is "<< total<<endl;
return 0;
}

Thanks a lot :D
#include <math.h>
This is C++. Use <cmath>

using namespace std;
This is bad practice. Don't do this.

main()
This is just plain wrong. main returns an int.

while(satuan > variable)
satuan has an undefined value at this point. Could be anything at all. You are making a comparison based on a number that could be anything at all. This is awful.

Last edited on
Pretty close, but to fix what moschops said and to solve the problem of:
1/1^2 - 1/2^2 + 1/3^2 - 1/4^2 until 1/n^2 < 0.000001
with more readability, it should be something more like

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 <cmath>
#include <iostream>

int main(int argc, char** argv)
{
    const double minimum = 0.000001;
    bool subtracting = false;
    double denominator, fraction;
    int n = 1;
    double total = 0;    

    do
    {
        // Calculate 1/n, store it, and then increment n for the next loop iteration
        denominator = pow(n, 2);
        fraction = 1/denominator;
        ++n;

        // Subtract or add and then switch operations for the next loop
        if (subtracting)
            total -= fraction;
        else
            total += fraction;
        subtracting = !subtracting;
    }
    while (fraction > minimum);
}
Topic archived. No new replies allowed.