From 4c260479dd7f673e90b3c4c50e1205a1de63386e Mon Sep 17 00:00:00 2001 From: Captain ALM Date: Fri, 14 Oct 2022 12:34:58 +0100 Subject: [PATCH] w2 q1 --- main.cpp | 90 +++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 60 insertions(+), 30 deletions(-) diff --git a/main.cpp b/main.cpp index 2d16d8a..f75ac0e 100644 --- a/main.cpp +++ b/main.cpp @@ -1,33 +1,63 @@ #include -#include -#include +#include +#include +#include -int main() -{ - using std::cout; - using std::cin; - srand(time(nullptr)); - int gcount{ 1 }; - int n { 20 }; - int secret { rand()%n + 1 }; - cout << "Guess a number between 1 and " << n << ": "; - int guess; - cin >> guess; - while (guess != secret) - { - if (guess > secret) - { - cout << "Number too big ; "; - } - else - { - cout << "Number too small ; "; - } - gcount++; - cout << "Guess again: "; - cin >> guess; - } - cout << "Correct!\n"; - cout << "Took " << gcount << " tries.\n"; - return 0; +using string = std::string; + +//Placw in header! +template +void printm(T m){ + std::cout << m; } + +template +void printlm(T m){ + printm(m); + printm("\n"); +} + +typedef std::vector::size_type vtype; + +double promptd(string,bool*); + +int main() { + std::setprecision(3); + printlm("Calculate median and average from sequence:"); + std::vector v{}; + bool s {}; + do { + auto d = promptd("Enter a number (Enter non-number to complete entry) : ",&s); + if (s) v.push_back(d); + } + while(s); + sort(v.begin(), v.end()); + printm("The count is: "); + printlm(static_cast(v.size())); + printm("The median is: "); + int halfway {static_cast(v.size()) / 2}; + if (static_cast(v.size())%2 == 1) + printlm(v.at(static_cast(halfway))); + else + printlm((v.at(static_cast(halfway - 1)) + v.at(static_cast(halfway))) / 2.0); + double avg {}; + for (vtype i = 0; i < v.size(); ++i) avg += v.at(i); + avg /= static_cast(v.size()); + printm("The average is: "); + printlm(avg); + return 0; +} + +double promptd(string message, bool *status) { + double tr {}; + *status = false; + std::cout << message; + if (!(std::cin >> tr)){ + std::cin.clear(); + std::cin.ignore(); + return 0; + } + *status = true; + return tr; +} +