#include <stdio.h>
#define SIZE 10
void function(int array[], int size, int compare, int* min, int* max);
int main() {
int max1, min1, n, m, array1[SIZE];
printf("Please enter an array size: ");
scanf("%d", &n);
printf("Enter numbers for array:");
for (int i = 0; i < n; i++) {
printf("enter number %d", i + 1);
scanf("%d", &array1[i]);
}
printf("Enter a number to be compared:");
scanf("%d", &m);
function(array1, n, m, &min1, &max1);
printf("There are %d numbers less than %d and there are %d numbers greater than %d",min1, m, max1, m);
}
void function(int array[], int size, int compare, int *min, int *max) {
for (int i = 0; i < size; i++) {
if (array[i] < compare)* min++;
if (array[i] > compare)* max++;
}
}
需要帮助了解为什么它只返回最小值和最大值的随机数。引用传递可能是它搞砸的原因,但我不知道我能做些什么来修复它。
最佳答案
您的代码有未定义的行为。
由于operator precedence (++
的优先级高于取消引用运算符 *
)
* min++;
翻译为
*(min++);
你需要的是
(*min)++;
更好的是,更改您的函数以接受引用类型并让您的生活更轻松。
void function(int array[], int size, int compare, int& min, int& max) {
for (int i = 0; i < size; i++) {
if (array[i] < compare) min++;
if (array[i] > compare) max++;
}
}
此外,请确保初始化 max1
和 min1
。否则,您的代码会使用未初始化变量的值,这会导致未定义的行为。
int max1 = 0;
int min1 = 0;
int n, m, array1[SIZE];
关于c - 查找大于和小于数组中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57619790/