我正在尝试获取 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
最佳答案
您在循环内声明最小值并输出,因此它会在每次迭代时执行此操作,现在开始:
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”,你的 vector 可能在某处有 0。但是您需要发布为此创建它的方式。
此外,您也可以只使用 numberList[i],不需要 .at()。
关于c++ - 寻找 vector 中的最小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58533308/