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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
//Steve Osborne, Using the Taylor Series
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
void Header();
void Input(double& prec,int& code);
int Factorial(int number);
void Summation(double prec,double& e,int& iter,bool& escape);
int SetPrecision(double prec);
void OutResults(double e,double iter,int decimals);
void LoopEscape();
int main(){
double prec;
int code=1;
bool escape=1;
int iter;
int decimals=1;
Header();
Input(prec,code);
while(code==1){
if(escape!=0){
double e=1;
Summation(prec,e,iter,escape);
if(escape!=0){
decimals=SetPrecision(prec);
OutResults(e,iter,decimals);
Input(prec,code);
}
}
}
return 0;
}
void Header(){
cout<<"Steve Osborne, Program 12"
<<"\nEuler's Number by Maclaurin Series"
<<"\nPlease enter the precision of e in this format: 1E-9";
return;
}
void Input(double& prec,int& code){
cout<<"\n\nEnter the precision of e or 0 to quit: ";
cin>>prec;
if(prec==0){
cout<<"\n\nGoodbye\n\n";
code=0;
}
else{
code=1;
}
return;
}
int Factorial(int number){
int fact=1;
for(int n=number;n>1;n--){
fact*=n;
}
return fact;
}
void Summation(double prec,double& e,int& iter,bool& escape){
int n=1;
double term=1;
iter=0;
while(term>prec&&iter<1000){
if(iter<=999){
e+=term;
n++;
term=1./Factorial(n);
iter++;
escape=1;
}
if(iter>999){
LoopEscape();
escape=0; //This should terminate the program in my eyes,
//changes escape to a 0 which kicks out of the loop in main
//and should go to my return 0; statement, it's not doing it though.
}
}
return;
}
int SetPrecision(double prec){
int precision=1;
precision=-(int)log10(prec);
return precision;
}
void OutResults(double e,double iter,int decimals){
cout<<"e = "<<fixed<<setprecision(decimals)<<e
<<" (with "<<fixed<<setprecision(0)<<iter
<<" iterations required)";
return;
}
void LoopEscape(){
cout<<"\n\nThe maximum number of iterations has been reached,"
<<"\n(1000+) this will terminate the program."
<<"\n\nGoodbye.\n\n";
return;
}
| |