用array和vector 數列求和取平均值
阿新 • • 發佈:2018-12-15
//array型別 #include <iostream> #include <string> #include<vector>; using namespace std; void main() { int iAy_add = 0; const int iAy_size = 10;//表示式必須含有常量值 int iArray[iAy_size];//array也像c-style一樣大小固定,但是不同的是array並沒有像null字元那樣所謂的“標兵”——用來表示已達到末端。 int user_size; cout << "plesae input your seq size " << endl; cin >> user_size; cout << "plesae input your seq " << endl; for (int i = 0; i <= user_size; i++) { cin >> iArray[i]; } for (int i = 0; i <= user_size; i++) { cout << iArray[i]<<' '; iAy_add += iArray[i];//簡寫的很棒哦 } cout << iAy_add << endl; int average = iAy_add / (user_size+1); cout << average << endl; int c; cin >> c; } //vector型別 #include <iostream> #include <string> #include<vector>; using namespace std; void main() { vector<int> ivec; cout << ivec.size() <<endl; int ival; int sum=0; int a = 1; while (a==1) { cin >> ival; ivec.push_back(ival);//push_back作用為在vector尾部加入一個數據;string也有這種用法,作用為在字串尾部加入一個字元 if (ival == 0) a=0; } for (int ix = 0; ix < ivec.size(); ++ix) { sum += ivec[ix]; } int average = sum / (ivec.size()-1); cout << "sum of" << ivec.size()-1 << " elements:" << sum << ". Average:" << average << endl; int c; cin >> c; }