检查数组中的所有整数是否相同- C

2nc8po8w  于 2022-12-11  发布在  其他
关注(0)|答案(3)|浏览(101)

我做了一个练习,要求用户决定数组的大小最大为30,填充,然后检查数组中包含的所有数字是否相等
我试过这种方法,但结果总是“数组的元素不都一样”,尽管它们都是。
有人能给予我一把吗?下面我插入了我已经写好的代码

#include <stdio.h>
#include <stdbool.h>

#define MAX_DIM 30

int check(int[], int);

int main(int argc, char *argv[]) {

    int dim;
    int num;
    int flag;
    int arr[MAX_DIM];

    printf("Insert an array dimension. \n");
    printf("Remember that the maximum size the array can take is %d \n\n", MAX_DIM);
    printf("Array dimension: ");
    scanf("%d", &dim);

    if (dim <= MAX_DIM) {
        arr[dim];
    } else {
        printf("Array dimension isn't valid! \n");
        return 0;
    }

    printf("\n");

    printf("Enter the numbers to place in the array of size %d ", dim);
    for (int i = 0; i < dim; i++) {
        scanf("%d", &num);
    }

    int equals = check(arr, dim);

    if (equals == 1) {
        printf("he elements of the array are all the same \n");
    } else {
        printf("he elements of the array are not all the same \n");
    }  

}

int check(int arr[], int dim) {
    
    for (int i = 0; i < dim; i++) {
        if (arr[i] != arr[i + 1]) {
            return -1;
        }
    }
    return 1;

}
dpiehjr4

dpiehjr41#

两个主要问题(以及其他次要问题):

  1. scanf语句正在填充变量num,但未填充数组,数组从未初始化。
  2. check函数中的循环应该在倒数第二个索引处停止。转到末尾意味着您正在与末尾的越界值进行比较。
#include <stdio.h>
#include <stdbool.h>

#define MAX_DIM 30

int check(int[], int);

int main(int argc, char *argv[]) {

    int dim;
    int num;
    int flag;
    int arr[MAX_DIM];

    printf("Insert an array dimension. \n");
    printf("Remember that the maximum size the array can take is %d \n\n", MAX_DIM);
    printf("Array dimension: ");
    scanf("%d", &dim);

    if (dim >= MAX_DIM) {
        printf("Array dimension isn't valid! \n");
        return 0;
    }

    printf("\n");

    printf("Enter the numbers to place in the array of size %d ", dim);
    for (int i = 0; i < dim; i++) {
        scanf("%d", arr + i);
    }

    int equals = check(arr, dim);

    if (equals == 1) {
        printf("The elements of the array are all the same \n");
    } else {
        printf("The elements of the array are not all the same \n");
    }  

}

int check(int arr[], int dim) {
    
    for (int i = 0; i < dim - 1; i++) {
        if (arr[i] != arr[i + 1]) {
            return -1;
        }
    }
    return 1;

}
xuo3flqw

xuo3flqw2#

您没有存储scanf中的值。请尝试以下操作:

for (int i = 0; i < dim; i++) {
        scanf("%d", &num);
        arr[i]=num;
    }
mtb9vblg

mtb9vblg3#

您没有设置实际数组值请将scanf调用替换为scanf("%d", &arr[i]);

相关问题