c++ - 为什么我的代码找不到第二小的元素数组?

int smallindex = 0;
int secsmallindex = 0;

我将上面的行放入 gobalslope。

其余代码:

#include <iostream> 
using namespace std;

int main() {
    int list[10] = { 33,6,3,4,55,22,5,6,7,6 };
    for (int a = 1; a <= 10; a++)
    {
        if (smallindex > list[a]) {
            secsmallindex = smallindex;
            smallindex = a;
        }
        else if (list[a] < secsmallindex && list[a] > smallindex) {
            secsmallindex = a;
        }
    }
    cout << secsmallindex << "   " << smallindex;
}

我想找到第二小的元素和最小的数字。

但是找不到。

输出是2和10。

回答1

你遇到了一些问题。主要是数组的索引范围,并将索引与存储在数组中的实际 value 进行比较。我注释掉了旧的(有问题的)行,并添加了正确的行和一些描述。 (https://godbolt.org/z/cWq1WTbhK

#include <iostream>

using namespace std;

int main() {
    /// You don't need these variables to be global.
    /// Minimise the scope of the variables!
    int smallindex = 0;
    int secsmallindex = 0;

    int list[10] = {33, 6, 3, 4, 55, 22, 5, 6, 7, 6};
    
    /// for (int a = 1; a <= 10; a++) <- old line
    /// In C and C++, array indexing is 0 based! Your last index is 9
    for (int a = 1; a < 10; a++)
    {
        /// if (smallindex > list[a]) <- old line
        /// You comparing the index to the ath element but you should
        ///     compare element to element
        if (list[smallindex] > list[a]) 
        {
            secsmallindex = smallindex;
            smallindex = a;
        }
        /// else if (list[a] < twosmallindex && list[a] > smallindex) <- old line
        /// Same as before, compare element to element not element to index
        else if (list[a] < list[secsmallindex] && list[a] > list[smallindex])
        {
            secsmallindex = a;
        }
    }
    cout << secsmallindex << " " << smallindex;
}

输出:3 2

回答2

您需要比较数组的元素。不是索引与元素

if(list[smallindex] > list[a])

相似文章

随机推荐

最新文章