要在数组中找到一个值,您应该遍历它并将每个值与所需的数值进行比较。您还应该检查返回值scanf()
以控制它实际读取的项目数。看看这个审查代码是否有帮助:
#include <stdio.h>
#define ARR_SIZE 10
int read_numbers(int a[], int size) {
int i = 0;
int r = 0;
while (i < size) {
printf("Please, enter a number (%d of %d): ",i+1,size);
r = scanf(" %d",&a[i]); // the space before will ignore any trailing newline
if (r == EOF) break; // if scanf fails return
if (r != 1) { // if user don't enter a number, repeat
printf("Wrong input!\n");
scanf("%[^\n]*"); // will read and ignore everything lweft on stdin till newline
continue;
}
++i;
}
return i; // return size, unless scanf fails
}
int find_number(int a[], int size, int x) {
int i = 0;
while (i < size && a[i] != x) ++i;
return i; // if x isn't in the array returns size
}
int main()
{
int my_arr[ARR_SIZE];
int secnum = 0;
int i = 0;
int n = 0;
n = read_numbers(my_arr, ARR_SIZE);
if (n < ARR_SIZE) {
printf("Warning, only %d numebers read out of %d!\n",n,ARR_SIZE);
} // if happens you have uninitialized elements in array
printf("Now, enter the value you want to find.\n");
if (read_numbers(&secnum, 1) != 1) { // reuse the function
printf("Sorry, an error has occurred.\n");
return -1;
}
i = find_number(my_arr, n, secnum); // If all went right n==ARR_SIZE
if (i < n) { // a match has been found
printf("Found!\n");
} else {
printf("Not found.\n");
}
return 0;
}
请descrip,不起作用。永远不要忽略'scanf()'的返回值总是检查。 –
'if'检查你的代码在哪里? – Pawan
错误:下标值既不是数组也不是指针。我不需要在指针中使用,而且我也不会错误地指出错误。如何解决它? – NoNameP