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;
}
usingnamespace 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.
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
#include <cmath>
#include <iostream>
int main(int argc, char** argv)
{
constdouble 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);
}