我试图确定数组中出现整数的次数,但我得到了一些意想不到的结果。
例如:
int arr1[10] = {1, 2, 2, 4, 4, 2, 5, 10, 2, 6};
std::cout << getOccurrences(arr1, 2) << std::endl; //should be 4
以下是完整代码:
#include "stdafx.h"
#include <iostream>
#include <array>
int getOccurrences(int arr[], int ch) {
int count = 0;
for (int i = 0; i < sizeof(arr); i++) {
if (arr[i] == ch) {
count++;
}
}
return count;
}
int main() {
int arr1[10] = {1, 2, 2, 4, 4, 2, 5, 10, 2, 6};
int arr2[10] = { 10, 21, 24, 44, 43, 24, 50, 10, 2, 6 };
int arr3[10] = { 11, 22, 22, 43, 44, 22, 51, 11, 2, 6 };
int arr4[10] = { 12, 12, 12, 4, 4, 12, 5, 10, 12, 6 };
int arr5[10] = { 21, 21, 21, 4, 4, 21, 5, 10, 21, 6 };
std::cout << getOccurrences(arr1, 2) << std::endl; //should be 4
std::cout << getOccurrences(arr2, 10) << std::endl; //should be 2
std::cout << getOccurrences(arr3, 22) << std::endl; //should be 3
std::cout << getOccurrences(arr4, 12) << std::endl; //should be 4
std::cout << getOccurrences(arr5, 21) << std::endl; //should be 5
return 0;
}
然而,在运行之后,我得到:
2
1
2
3
3
有人可以向我解释为什么会这样吗?感谢。