首页 > 解决方案 > 在数组中查找大于和小于的数字

问题描述

#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++;
    }
}

需要帮助了解为什么它只返回最小值和最大值的随机数。引用传递可能是搞砸了,但我不知道我能做些什么来修复它。

标签: cpass-by-reference

解决方案


您的代码具有未定义的行为。

由于运算符优先级++比取消引用运算符具有更高的优先级*

* 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++;
    }
}

另外,请确保初始化max1min1. 否则,您的代码会使用未初始化变量的值,这会导致未定义的行为。

int max1 = 0;
int min1 = 0;
int n, m, array1[SIZE];

推荐阅读