-
Nested loop Problems
How can I use nested loop to solve the problem below?
Calculate the valuse of x from the infinite series
x=4- 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + .......
Print a table that shows the value of x approximated by 1,2,3,etc, terms.
What I wrote is:
#include <iostream.h>
#include <iomanip.h>
#include <math.h>
void print(double x,int n)
{
cout << (long int) (x) << '.';
for( ; n>0; n--)
{
x = x - (long int) (x);
x = 10. * x;
cout << int(x);
}
}
double dec(double x, int n)
{
double p;
p = pow(10.,n);
return ((long int)(x*p + ((x>0.) ? 0.499999 : -0.499999)))/p;
}
int main()
{
int n;
double f, x = 3.141515151515;
for (cout<< '\n', n=0; n<15; n++)
{cout << '\n' ;print(x, n); }
cout << '\n';
return 0;
}
However, my teacher said that it's completely wrong! So, can anyone tells me how to do the problem by using nested loop?
thank you very much!!:)
-
Why do you need two loops?
Code:
#include <stdio.h>
// x=4- 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + .......
// re-written as
// x= 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + .......
int main ( ) {
double denom = 1;
double plusminus = 1.0;
double x = 0;
int i;
for ( i = 0 ; i < 10 ; i++ ) {
x = x + 4.0 / ( denom * plusminus );
printf( "Term=%d, result=%f, denom=%.0f\n", i, x, denom*plusminus );
denom = denom + 2.0;
plusminus = -plusminus;
}
return 0;
}
-