這是一個問題,我的工作:無論我作爲輸入使用,輸出全零
- 提示用戶輸入五個數字,是五個人的權重。將數字存儲在雙打的矢量中。在一行中輸出矢量的數字,每個數字後跟一個空格。
通過對矢量的元素求和,還輸出總權重。
還輸出矢量元素的平均值。
還輸出最大向量元素。 到目前爲止,這是我的代碼有
#include <iostream> #include <vector> using namespace std; int main() { const int NEW_WEIGHT = 5; vector<float> inputWeights(NEW_WEIGHT); int i = 0; float sumWeight = 0.0; float AverageWeight = 1.0; int maxWeight = 0; int temp = 0; for (i = 0; i < NEW_WEIGHT; i++){ cout << "Enter weight "<< i+1<< ": "; cout << inputWeights[i]<< endl; cin>> temp; inputWeights.push_back (temp); } cout << "\nYou entered: "; for (i =0; i < NEW_WEIGHT- 1; i++) { cout << inputWeights.at(i)<< " "; } cout<< inputWeights.at(inputWeights.size() - 1) << endl; for (i =0; i < NEW_WEIGHT; i++){ sumWeight += inputWeights.at(i); } cout <<"Total weight: "<< sumWeight<< endl; AverageWeight = sumWeight/inputWeights.size(); cout <<"Average weight: "<< AverageWeight<< endl; maxWeight= inputWeights.at(0); for (i =0; i < NEW_WEIGHT- 1; i++){ if (inputWeights.at(i) > maxWeight){ maxWeight = inputWeights.at(i); } } cout<< "Max weight: "<< maxWeight << endl; return 0; }
當我運行這段代碼,我使用什麼輸入(CIN將>>(...)),我得到全零作爲輸出和我不知道爲什麼。請給我一些幫助。
更新 清理代碼一點通過擺脫COUT < < inputWeights [I] < < ENDL的;
並通過調整向量inputWeights;在程序的開始。但輸出仍然不完全是他們應該是。相反,只有前2個輸入值才能作爲輸出。任何理由?謝謝
更新這是正確的或正確的代碼。希望它能幫助未來的人。
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector <float> inputWeights;
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
float maxWeight = 0.0;
float temp = 0.0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": "<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++){
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight/inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
提示:怎麼看待的push_back()的作品 – LWimsey
@LWimsey其追加無論是在臨時的載體inputWeights。 – TINA15
,所以你的矢量從5增加到10,因爲你用5個零來初始化它,而那些仍然存在來自所有反饋的 – LWimsey