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
|
/* Hannah Winsor, Uses loop to sum fractions, Last modification 3/15/2015
This program uses a loop to sum a user-defined number of terms, n, in the series
1-1/2+1/3-1/4+1/5-...
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
//Declare variables
int n;
//float n;
double s, t, sum1, sum2, sum;
//Output program description, and ask for number of terms
cout << "This program uses a loop to sum a user-defined number of terms, n, in the series"
<< "1-1/2+1/3-1/4+1/5-..." << endl;
cout << "Please indicate how many terms you would like in the summation?\n";
cin >> n;
//For loop selected, most straightforward way to do the summation
if (n%2 ==0) //For even number of selected terms
{
for(n; n>0; n-=2) //adds the first n terms
{
s=(-1.0)*1.0/n; //All even terms
t=1.0/(n-1.0); //All odd terms
sum1+=s; // This sums all even terms, which are negative for this series, thus added separately
sum2+=t; // This sums all odd terms, which are positive for this series
}
}
else //(n%2==1), For odd number of selected terms
{
for(n; n>0; n-=2) //adds the first n terms
{
s=1.0/n; //All odd terms
t=(-1.0)*1.0/(n-1.0); //All even terms
sum1+=s; // This sums all odd terms, which are positive for this series
sum2+=t; // This sums all even terms, which are negative for this series, thus added separately
}
}
sum=1+sum1+sum2;
cout << "Using your indicated number of terms, your summation is " << setprecision(7) << sum;
return 0;
}
|