[英]Trying to find the smallest value and its index along a std vector in cpp
[英]Find the smallest value in a vector
在使用STL進行編程時,我還很陌生,我想我已經掌握了它。 但是我對此有些困惑。 我的目標是接受5個值,然后打印出我的值,打印其中的最高值,打印平均值,然后打印其中的最低值(我的問題)。 看來我的變量“低”的值是0,但我不知道為什么。 我已經測試過,看看是否能讀懂我的價值觀。 因此,如果有人可以啟發我,為什么我似乎無法獲得適當的最低價值,我將不勝感激。 感謝您的時間。
vector<double> vecList;
int x = 0;
double high = 0;
double low = 0;
double sum = 0;
cout << "Enter Integer Values, then press Ctrl(z) to Quit:" << endl;
for (int i=0; i < 5; i++)
{
cin >> x;
sum = sum + x;
vecList.push_back(x);
}
vector<double>::iterator intVecIter;
cout <<"List contains: ";
for (intVecIter = vecList.begin(); intVecIter != vecList.end(); ++intVecIter)
cout << *intVecIter << " ";
for (int i=0; i < 5; i++)
{
if(vecList[i] > high)
{
high = vecList[i];
}
// prints out "0"
if(low > vecList[i])
{
low = vecList[i];
}
}
cout << endl << "Largest: "<< fixed << setprecision(2) << high << endl;
cout << "Smallest: "<< fixed << setprecision(2) << low << endl;
cout << "Average: " << fixed << setprecision(2)<< (sum/5);
return 0;
由於您正在嘗試學習STL,因此請看一下算法庫 ,它具有一些輔助函數,這些函數將給出給定范圍的最小值,最大值和總和(累計為實際函數名稱)。
您需要將低值初始化為一個大值,而不是0,否則
if(low > vecList[i])
永遠不是真的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.