[英]Finding Smallest Number in Vector
我試圖獲得向量中的最小數字,但我的代碼每次運行時都會輸出 000。
我試過查看有關堆棧溢出的其他問題,但似乎其他人沒有收到與我類似的錯誤。
cout << "The smallest number is: ";
for (i = 0; i < numberList.size(); ++i) {
int smallest = numberList.at(0);
if (numberList.at(i) < smallest) {
smallest = numberList.at(i);
}
cout << smallest;
}
當我輸入 3 個數字時:1 2 3(作為單獨的輸入)我得到最小的數字是:000
您正在聲明最小並在循環內輸出,因此它將在每次迭代中執行此操作,這里是 go:
std::cout << "The smallest number is: ";
int smallest = numberList.at(0);
for (int i = 0; i < numberList.size(); ++i) {
if (numberList.at(i) < smallest) {
smallest = numberList.at(i);
}
}
std::cout << smallest;
如果你得到“0”,你的向量可能在某個地方有 0。 但是您需要發布如何為此創建它。
另外,你也可以只使用numberList[i],你不需要.at()。
你可以使用std::min_element來做你想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.