Skip to content

Instantly share code, notes, and snippets.

@jamesy0ung
Created October 18, 2024 06:10
Show Gist options
  • Save jamesy0ung/e7d259806b61e659db85f839af433f40 to your computer and use it in GitHub Desktop.
Save jamesy0ung/e7d259806b61e659db85f839af433f40 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
long double e = 1.0;
long double term = 1.0;
int i = 1;
long double precision = 1.0e-10;
bool flag_found = false;
int main(int argc, char* argv[])
{
std::cout << "Euler's Number Calculator\n";
for (int j = 1; j < argc; j++) {
if (std::string(argv[j]) == "-p") {
if (j + 1 < argc) {
int decimal_places = std::stoi(argv[j + 1]);
precision = std::pow(10.0, -decimal_places);
flag_found = true;
std::cout << "Calculating to " << decimal_places << " decimal places.\n";
}
else {
std::cout << "Precision has not been specified correctly.\n";
return 1;
}
}
}
if (!flag_found) {
std::cout << "No precision specified. Calculating to default precision (10 decimal places).\n";
}
while (term > precision)
{
term = term / i;
e = e + term;
i++;
};
int output_precision = std::ceil(-std::log10(precision));
std::cout << std::setprecision(output_precision);
std::cout << "Computed value of e is: " << e << std::endl;
std::cout << "Number of iterations: " << i - 1 << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment