c - 在数组中查找大于和小于的数字
问题描述
#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++;
}
}
需要帮助了解为什么它只返回最小值和最大值的随机数。引用传递可能是搞砸了,但我不知道我能做些什么来修复它。
解决方案
您的代码具有未定义的行为。
由于运算符优先级(++
比取消引用运算符具有更高的优先级*
)
* 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];
推荐阅读
- python - 如何知道 Python 中当前使用的是哪个 GPU 设备?
- android - 使用 Delphi for Android 显示 TMediaPlayer.Duration 和 TMediaPlayer.CurrentTime 的秒数
- typescript - 为什么我不能在 ThreeJS Typescript 项目中创建 Face3
- git - 将粘贴和替换文件复制到本地 git 存储库
- amazon-web-services - AWS Amplify - GraphQL 与现有认知用户池的多对多关系
- python-3.x - Amazon EC2 中的 pip3 install --force-reinstall -r requirements.txt 错误
- javascript - 我已经包含了数据表 cdn,但它不起作用
- python - 5 维权重的预期 5 维输入,但得到 4
- javascript - 在nodeJs中登录的空数组
- react-native - 反应本机开关显示为真但值为假为什么?