Read n and then n integers; print the sum, the average to two decimals, the smallest and the largest.
Solution
main.cpp
#include <algorithm>
#include <iomanip>
#include <iostream>
int main() {
int n;
std::cin >> n;
int first;
std::cin >> first;
long long sum = first;
int lo = first, hi = first;
for (int i = 1; i < n; ++i) {
int x;
std::cin >> x;
sum += x;
lo = std::min(lo, x);
hi = std::max(hi, x);
}
std::cout << "sum " << sum << ", average " << std::fixed << std::setprecision(2)
<< static_cast<double>(sum) / n << ", min " << lo << ", max " << hi << '\n';
return 0;
}
Output Verified by compiling and running
sum 60, average 12.00, min -4, max 30
Starting min and max at the first value avoids special starting constants. The cast to double keeps the fraction of the average.
More Input/Output with cin and cout practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!