Skip to content

Instantly share code, notes, and snippets.

@timcash
Created December 9, 2012 20:55
Show Gist options
  • Save timcash/4246946 to your computer and use it in GitHub Desktop.
Save timcash/4246946 to your computer and use it in GitHub Desktop.
Harmonic series
#include <iostream>;
#include <string>;
#include <cmath>;
using namespace std;
int main()
{
int n=0; //counter
int t=0; //user-input number of iterations
double young=0.0; //the new sum
double old=0.0; //the last sum
bool keep_going=true;
cout << "How many times do you want to iterate? ";
cin >> t;
while(keep_going==true)
{
//Add these lines so you can see the values as they iterate. Helps debug
//use endl to pring one per line
cout << "---------------------" << endl;
cout << "Loop # : " << n << endl;
cout << "old : " << old << endl;
cout << "1+n : " << 1+n << endl;
cout << "1/(1+n): " << 1/(1+n) << endl; //look carefully at this line and the next
cout << "1/(1+n): " << 1.0/(1+n) << endl; //see I added the .0
cout << "1/(1+n): " << 1/(1.0+n) << endl; //same idea
cout << "1/(1+n): " << (double)1/(1+n) << endl; //same idea again just a different way
//you should see that the 1/(1+n) is getting "casted" to an integer
//in other words is getting rounded to 0 when 1/2 or 1/3
//look up type casting in c++ on goolge for more info
//young=(old+1/(1+n));
young=(old+1.0/(1+n)); //main function that adds the last value to a slightly smaller fraction
cout << "young after computation: " << young << endl;
old=young;
n++;
if(n==t)
keep_going = false;
}
cout << "The total you requested is: " << young << endl;
cout << "Would you kindly press a key to continue?";
cin >> t;
return 0;
}
@timcash
Copy link
Author

timcash commented Dec 9, 2012

Added two lines to the while loop so you can see the values of young and old at each iteration

@timcash
Copy link
Author

timcash commented Dec 9, 2012

Added a bunch of cout so you can see what is happening with the type casting

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment