1
0
LearningCPP/main.cpp

62 lines
1.2 KiB
C++
Raw Normal View History

2022-10-14 09:27:47 +01:00
#include <iostream>
2022-10-19 09:33:42 +01:00
#include <vector>
#include <algorithm>
#include <iomanip>
2022-10-14 09:27:47 +01:00
using string = std::string;
2022-10-19 09:33:42 +01:00
//Placw in header!
template <typename T>
void printm(T m){
2022-10-14 09:27:47 +01:00
std::cout << m;
}
2022-10-19 09:33:42 +01:00
template <typename T>
void printlm(T m){
2022-10-14 09:27:47 +01:00
printm(m);
printm("\n");
}
2022-10-19 09:33:42 +01:00
double promptd(string,bool*);
int main() {
std::setprecision(3);
printlm("Calculate median and average from sequence:");
std::vector<double> v{};
bool s {};
do {
auto d = promptd("Enter a number (Enter non-number to complete entry) : ",&s);
if (s) v.push_back(d);
2022-10-14 09:27:47 +01:00
}
2022-10-19 09:33:42 +01:00
while(s);
sort(v.begin(), v.end());
printm("The count is: ");
printlm(v.size());
printm("The median is: ");
int halfway {static_cast<int>(v.size()) / 2};
if (static_cast<int>(v.size())%2 == 1)
printlm(v.at(halfway));
else
printlm((v.at(halfway - 1) + v.at(halfway)) / 2.0);
double avg {};
for (int i = 0; i < static_cast<int>(v.size()); ++i) avg += v.at(i);
avg /= static_cast<int>(v.size());
printm("The average is: ");
printlm(avg);
return 0;
2022-10-14 09:27:47 +01:00
}
2022-10-19 09:33:42 +01:00
double promptd(string message, bool *status) {
double tr {};
*status = false;
2022-10-14 09:27:47 +01:00
std::cout << message;
2022-10-19 09:33:42 +01:00
if (!(std::cin >> tr)){
2022-10-14 09:27:47 +01:00
std::cin.clear();
std::cin.ignore();
2022-10-19 09:33:42 +01:00
return 0;
2022-10-14 09:27:47 +01:00
}
2022-10-19 09:33:42 +01:00
*status = true;
2022-10-14 09:27:47 +01:00
return tr;
}
2022-10-19 09:33:42 +01:00