C++练习题4:输入20个数,求其最大、最小和平均值
// stdycpp04.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
/*输入20个数,求其最大、最小和平均值
* 方案一、用比大小的方法,将最大值,最小值,总和求出,然后计算打印
* 方案二、建立数组,用容器将数装入进去,然后求值。
*/
1 #include <iostream> 2 //容器类:动态数组 3 #include<vector> 4 //迭代器:容器vector的一些计算函数 5 #include<algorithm> 6 //迭代器:容器的一些数值计算 7 #include<numeric> 8 9 10 using namespace std; 11 12 class myclass { 13 public: 14 myclass(); 15 ~myclass(); 16 void mymethod(); 17 void mymethod1(); 18 19 }; 20 21 myclass::myclass() { 22 23 } 24 myclass::~myclass() { 25 26 } 27 28 void myclass::mymethod1() { 29 double a; 30 cout << "请输入20个数字,以回车结束" << endl; 31 vector<double> list1; 32 for (int i = 0; i < 20; i++) { 33 cin >> a; 34 list1.push_back(a); 35 } 36 cout << "最大值是:" << *max_element(list1.begin(),list1.end()) << endl; 37 cout << "最小值是:" << *min_element(list1.begin(),list1.end()) << endl; 38 cout << "平均值是:" << accumulate(list1.begin(),list1.end(),0.0)/list1.size() << endl; 39 40 } 41 42 void myclass::mymethod() { 43 double a, minnumber, maxnumber, total; 44 cout << "请输入20个数字,以回车结束" << endl; 45 cin >> a; 46 total = minnumber = maxnumber = a; 47 for (int i = 1; i < 20; i++) { 48 cin >> a; 49 if (maxnumber < a) { 50 maxnumber = a; 51 } 52 if (minnumber > a) { 53 minnumber = a; 54 } 55 total = total + a; 56 } 57 cout << "最大值是:" << maxnumber << endl; 58 cout << "最小值是:" << minnumber << endl; 59 cout << "平均值是:" << total / 20 << endl; 60 } 61 62 63 int main() 64 { 65 myclass myc; 66 // myc.mymethod(); 67 myc.mymethod1(); 68 return 0; 69 // std::cout << "Hello World!\n"; 70 }

浙公网安备 33010602011771号