识别数组在C++中的最小索引位置
identifying smallest index position of array in C++
我是新来的。 我搜索了现有问题以寻找这个问题的答案,它确实帮助我进步,但我拥有的代码仍然返回"0"而不是数组中最小值索引中的实际位置。
任何帮助将不胜感激,谢谢。
#include<iostream>
using namespace std;
int smallestIndex(int arr[], int size);
int main()
{
int arr[6] = {500, 29, 36, 4, 587, 624};
cout << "Index position for smallest element in array: "
<< smallestIndex(arr, 6) << endl;
return 0;
}
int smallestIndex(int arr[], int size)
{
int temp;
int n = arr[0];
for (int i = 0; i > size; i++)
{
if (arr[i] < n)
n = arr[i];
temp = i;
}
return temp;
}
- 条件
i > size
是错误的。应该是i < size
. - 不要忘记初始化
temp
。将其写为int temp = 0;
,因为n
的初始值是数组的第 0 个元素。 - 您忘记使用块,
temp
的值将是错误的。
固定代码:
int smallestIndex(int arr[], int size)
{
int temp = 0;
int n = arr[0];
for (int i = 0; i < size; i++)
{
if (arr[i] < n)
{
n = arr[i];
temp = i;
}
}
return temp;
}
相关文章:
- 访问特定阵列位置/索引时出现分段错误
- 素数索引位置C程序
- 如何计算 3d 数组中的索引值在内存中的位置?如何计算字符**中的索引值在内存中的位置?
- GLES计划资源索引/位置与统一索引/位置
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- 我可以将单个顶点索引与具有所有属性(位置、法线、texCoord)的顶点缓冲区一起使用吗?
- C++ std::map 如何按索引位置访问密钥
- C++ 提升日志位置(索引)格式对齐
- 如何返回索引位置而不是值
- C++如何在获取子字符串的索引位置后获取子字符串
- C++:写入 std::string 中的特定索引位置
- 二进制搜索返回其所属位置的索引
- 识别数组在C++中的最小索引位置
- 需要 std::set 元素的位置/索引
- 查找向量中的值索引位置
- 获取元素在boost::multi_index_container的顺序索引中的位置
- 正在将指针从数组值存储到原始数组索引位置
- 2d查找重复元素/获取索引位置并计数重复项
- 用户正在输入10个数字,找到最大的负值及其索引/位置
- Rgd:用于获取索引位置的矢量迭代器