有人可以指出哪里出了问题吗?值 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/