Advertisement
Guest User

Untitled

a guest
Sep 30th, 2014
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. /**
  2. * @file pi.cpp
  3. * @brief Calculates pi for the given number of terms
  4. * @author syb0rg
  5. * @date 10/3/14
  6. */
  7.  
  8. #include <iostream>
  9. #include <limits>
  10. #include <cctype>
  11. #include <cmath>
  12.  
  13. /**
  14. * Makes sure data isn't malicious, and signals user to re-enter proper data if invalid
  15. */
  16. void getSanitizedDouble(long double &input)
  17. {
  18. while (!(input = std::cin.peek()) && input != 'n')
  19. {
  20. if (std::isalpha(input) || std::isspace(input)) std::cin.ignore(); // ignore alphabetic and space characters from input
  21. }
  22. while(!(std::cin >> input) || input < 0)
  23. {
  24. std::cin.clear(); // clear the error flag that was set so that future I/O operations will work correctly
  25. std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); // skips to the next newline
  26. std::cout << "Invalid input. Please enter a positive number: ";
  27. }
  28. }
  29.  
  30. int main()
  31. {
  32. long double num = 0.;
  33. char again = '';
  34. do
  35. {
  36. long double pi = 0.;
  37.  
  38. // get input for height, re-read input if not a positive number
  39. std::cout << "Enter the number of terms to approximate π: ";
  40. getSanitizedDouble(num);
  41.  
  42. for(auto i = 0; i < num; i++)
  43. {
  44. pi += std::pow(-1, i) / (2 * i + 1);
  45. }
  46. pi *= 4;
  47.  
  48. std::fprintf(stdout, "Approximated value of π for %Lg terms: %Lgn", num, pi);
  49.  
  50. std::cout << "Run the program again (y/N): "; // signify n as default with capital letter
  51. std::cin.get(); // absorb newline character from previous input
  52. std::cin.get(again);
  53. again = std::tolower(again);
  54. } while (again == 'y');
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement