c - 1 和 0 存在于空 int 数组中

标签 c arrays initialization undefined

有人可以指出哪里出了问题吗?值 0 和 1 总是出现在 if 中并返回 true。 (假设数组为空)。

#include <stdio.h>
#include <stdbool.h>
#define ARRAY_SIZE 5

int getUserInput(int position){
    printf("Please enter an integer for the %d position of the array\n", position);
    int input;
    scanf(" %d", &input);
    return input;
}

bool hasValue(int value, int array[ARRAY_SIZE]){
    int i;
    for(i = 0; i < ARRAY_SIZE; i++){

        if (value == array[i]){
            printf("This value already exists in the array.\n");
            return true;
        }
    }
    return false;
}

main(){
    int array[ARRAY_SIZE];
    int index = 0;

    while (index < ARRAY_SIZE ){
        int input = getUserInput(index);

        if (!hasValue(input, array)){
            array[index] = input;
            index++;
        }
     }
}

最佳答案

最好将数组 size 作为参数传递给函数,而不是修复它。喜欢

bool hasValue(int value, int array[], unsigned int size)

由于您的 ARRAY_SIZE 是一个常量,因此函数内的 for 循环始终执行 ARRAY_SIZE 次。

编辑 如果您的代码仍然没有解决问题。用此替换相关代码并尝试

bool hasValue(int value, int array[], int size) {
    int i;
    for(i = 0; i < size; i++) {
        if (value == array[i]) {
            printf("This value already exists in the array.\n");
            return true;
        }
    }
    return false;
}

int main() {
    int array[ARRAY_SIZE];
    int index = 0;

    while (index < ARRAY_SIZE ) {
        int input = getUserInput(index);

        if (!hasValue(input, array, index)) {
            array[index] = input;
            index++;
        }

     }

     return 0;
}

关于c - 1 和 0 存在于空 int 数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48979098/

相关文章:

c - Xcode 和终端中的不同输出

python - 与 Numpy 不同,Pandas 似乎不喜欢内存步幅

c++ - 函数指针数组初始化

C++ STL vector 初始化

c - 如何确定要使用哪个 SOC 或 SDK 板?

c - 设置 MPI_Info : value is too long 时出错

arrays - 将异构变量数组转换为结构的函数(保留名称)

java - 检查数组中的空元素

c++ - 类成员在实例初始化时需要这个指针

c - 如何在 C (unix) 中读取 mp3 文件标签?