#include <iostream>
#include <iomanip>
#include <cmath>
usingnamespace std;
int main()
{
int iter, m, n=0, it = -1 , cnt =0;
double sum , pi1 = sqrt(12), rt =0;
cout <<"This program estimates the value of PI using the Babylonian method.\n\n";
cout <<"Enter a count that will be used for series iteration: ";
cin >> iter; cout <<"\n";
cout << fixed <<setprecision(14);
if (iter == 0)
{
cout <<"The input count must be greater than 0.\n";
cout <<"Try entering again: ";
cin>>iter;
cout <<"\n";
}
while ((n - iter)<=-1 )
{
it *= -1;
++cnt;
m = 3 + (2*(n-1));
sum = it / (m * pow(3,n));
rt += sum;
++n;
cout << setw(2)<<cnt <<" "<< pi1 * rt<<endl;
}
return 0;
}
as you can see if i enter 10 in cin >> iter . the output will be like
1 ....
2 ....
3 ....
4 ....
5 ....
6 ....
7 ....
8 ....
9 ....
10 ....
but the last line of the program i want to write a code line to display the last output of the loop so it can be like this:
1 ....
2 ....
3 ....
4 ....
5 ....
6 ....
7 ....
8 ....
9 ....
10 ....
the last output is ...... // the .... is the result belongs to the 10th line (which means the last line ).
#include <iostream>
#include <iomanip>
#include <cmath>
usingnamespace std;
int main()
{
int iter, m, n=0, it = -1 , cnt =0;
double sum , pi1 = sqrt(12), rt =0;
cout <<"This program estimates the value of PI using the Babylonian method.\n\n";
cout <<"Enter a count that will be used for series iteration: ";
cin >> iter; cout <<"\n";
cout << fixed <<setprecision(14);
if (iter == 0)
{
cout <<"The input count must be greater than 0.\n";
cout <<"Try entering again: ";
cin>>iter;
cout <<"\n";
}
double lastsaved = 0; // declare a variable outside the loop <----//
while ((n - iter)<=-1 ) //
{ //
it *= -1; //
++cnt; //
m = 3 + (2*(n-1)); //
sum = it / (m * pow(3,n)); //
rt += sum; //
++n; //
//
lastsaved = pi1 * rt; // then update it inside the loop <-----//
cout << setw(2) << cnt << " " << lastsaved << endl;
}
std::cout << "the last output is " << lastsaved << '\n';
return 0;
}