[英]Why can’t my code find the second smallest elements array?
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。
你遇到了一些問題。 主要是數組的索引范圍,並將索引與存儲在數組中的實際值進行比較。 我注釋掉了舊的(有問題的)行,並添加了正確的行和一些描述。 (演示)
#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
您需要比較數組的元素。 不是索引與元素
if(list[smallindex] > list[a])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.