我正在编写代码打印出固定大小 4 的数组 中出现至少3 次 中最频繁出现的数字强>.
例如:
int arr[4] = {9,2,9,9}
Number that occurs at least 3 times is: 9
int arr[4] = {9,9,9,9}
Number that occurs at least 3 times is: 9
int arr[4] = {-1,3,3,3}
Number that occurs at least 3 times is: 3
int arr[4] = {9,-1,9,9}
Number that occurs at least 3 times is: 9
int arr[4] = {1,1,2,2}
Number that occurs at least 3 times is: None
我试过:
int arr[4] = {9,2,9,9};
int i;
int count;
int value;
int first;
int length = sizeof(arr) / sizeof(int);
int count = 0;
for (i=1;i<length-1;i++) {
first = arr[0];
if (first == arr[i]) {
value = arr[i];
count +=1;
}
}
if (count >= 3) {
printf("Number that occurs at least 3 times is: %d",value);
}
else {
printf("Number that occurs at least 3 times is: None");
}
但是我得到了输出:
Number that occurs at least 3 times is: None
应该是:
Number that occurs at least 3 times is: 9
我错过了什么?非常感谢这方面的帮助。
因为你的for循环只运行了2次,count最多只能是2。
我是一名优秀的程序员,十分优秀!