Advertisement
Derga

Untitled

Sep 16th, 2023
929
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.25 KB | None | 0 0
  1. #include <charconv>
  2. #include <iomanip>
  3. #include <iostream>
  4. #include <string>
  5.  
  6. using namespace std;
  7.  
  8. /*
  9. Требование 6) к лб звучит так -
  10. "код должен производить форматированный вывод результатов".
  11.  
  12. Так как тип выходных данных - long double - у нас есть возможность выводить его с заданной точностью.
  13. Так как по условию задачи у нас нет входных данных задающих эту "точность" -
  14. давайте объявим ее глобальной константой.
  15. */
  16. const size_t presicion = 10;
  17.  
  18. long double GetLongDouble() {
  19.     long double result;
  20.     do
  21.     {
  22.         string str;
  23.         getline(cin, str);
  24.  
  25.         auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), result);
  26.         if (ec == std::errc::invalid_argument)
  27.         {
  28.             std::cout << "This is not a number.\n";
  29.         }
  30.         else if (ec == std::errc::result_out_of_range)
  31.         {
  32.             std::cout << "This number is larger than an long double.\n";
  33.         }
  34.         else
  35.         {
  36.             return result;
  37.         }
  38.  
  39.         cout << "Please enter number again\n";
  40.     } while (true);
  41. }
  42.  
  43. long double GetMass() {
  44.     double mass = GetLongDouble();
  45.  
  46.     while (mass <= 0)
  47.     {
  48.         cout << "The mass of the point should be greater than 0.\n"
  49.          << "Enter the mass of the point again\n";
  50.  
  51.         mass = GetLongDouble();
  52.     }
  53.    
  54.     return mass;
  55. }
  56.  
  57. void CalculateCenterOfMass() {
  58.     cout << "Enter coordinate of the point x1\n";
  59.     long double x1 = GetLongDouble();
  60.     cout << "Enter mass of the point x1\n";
  61.     long double mass1 = GetMass();
  62.     cout << "Enter coordinate of the point x2\n";
  63.     long double x2 = GetLongDouble();
  64.     cout << "Enter mass of the point x2\n";
  65.     long double mass2 = GetMass();
  66.    
  67.     cout << "The coordinate of the center of mass is "
  68.          << setprecision(presicion)
  69.          << (x1 * mass1 + x2 * mass2) / (mass1 + mass2) << '\n';
  70. }
  71.  
  72. bool DoYouWantCalculateCenterOfMassAgain() {
  73.     cout << "Enter \"yes\" if you want to calculate the center of mass again\n";
  74.     string replay;
  75.     getline(cin, replay);
  76.     if (replay == "yes") {
  77.         return true;
  78.     }
  79.     return false;
  80. }
  81.  
  82. int main() {
  83.     do {
  84.         CalculateCenterOfMass();
  85.     } while (DoYouWantCalculateCenterOfMassAgain());
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement