// CSE1502 Spring 2009 Homework #4, Matt Mahoney // This program inputs a number n and prints e to n decimal places. #include #include using namespace std; // Divide a by b and put the result back in a, where a is a string of // digits and b > 0. void divide(string & a, int b) { int carry = 0; for (int i=0; i= 0; --i) { a[i] += (b[i] - '0' + carry); if (a[i] > '9') { a[i] -= 10; carry = 1; } else carry = 0; } return a; } // Get n and calculate e to n decimal places int main() { // Get n = number of digits from user int n; cout << "How many decimal places of e would you like? "; cin >> n; // calcuate e = 1 + 1/1! + 1/2! + 1/3! + 1/4! +... until term is 0 string e = "1" + string(n, '0'); string term = e; string zero = string(n+1, '0'); for (int i=1; term != zero; ++i) { divide(term, i); e = add(term, e); } // Insert decimal point in result cout << "e = " << e[0] << "." << e.substr(1) << endl; return 0; }