要在數組中找到一個值,您應該遍歷它並將每個值與所需的數值進行比較。您還應該檢查返回值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