我想知道用户输入的数字是否是数组中的数字。
这是我的代码:
#define ARR_SIZE 10
int main()
{
int my_arr[10];
int secnum = 0;
int i = 0;
for (i = 0; i < ARR_SIZE ; i++)
{
printf("Enter a number: ");
scanf("%d",&my_arr[i]);
}
printf("Enter the another number");
scanf("%d",&secnum);
if(my_arr[i] == secnum)
{
printf("an ex");
}
}
但它不起作用。
如何将数字与数组中的其他数字进行比较?
注意:我不知道指针所以我需要在没有指针的情况下进行操作。
答案 0 :(得分:1)
为什么它不起作用以及代码有什么问题?
i
循环后scanf
的值为10,因此arr[i]
将超过#define ARR_SIZE 10
int main()
{
int my_arr[ARR_SIZE]; //Use ARR_SIZE because if ARR_SIZE changes, 10 won't causing unforseen errors.
int secnum = 0;
int i = 0;
for (i = 0; i < ARR_SIZE ; i++)
{
printf("Enter a number: ");
scanf("%d",&my_arr[i]);
}
printf("Enter the another number");
scanf("%d",&secnum);
for (i = 0; i < ARR_SIZE ; i++) // Ensures you are comparing secnum with each array element.
{
if(my_arr[i] == secnum)
{
printf("an ex"); //Do you wish to break here because one you find a match, the goal is attained :)
}
}
}
数组并可能导致非法内存访问。检查程序中的注释。
ronda
答案 1 :(得分:0)
循环后,i等于ARR_SIZE
(10
)。因此,您将my_arr[10]
与secnum
(0
)进行比较。但my_arr[10]
虽然语法正确,但指向未定义的值,因为数组的大小为10
。
答案 2 :(得分:0)
#define ARR_SIZE 10
int main()
{
int my_arr[10];
int secnum = 0;
int i = 0;
for (i=0;i<ARR_SIZE ; i++)
{
printf("Enter a number: ");
scanf("%d",&my_arr[i]);
}
printf("Enter the another number");
scanf("%d",&secnum);
for (i=0;i<ARR_SIZE ; i++)
{
if(my_arr[i]==secnum)
{
printf("Given number is in array\n");
break;
}
}
}
答案 3 :(得分:0)
正如OP对其中一个答案的评论所指出的,OP显然需要一个例程来检查数组中的键。
因此,一旦我们存储了array
并已接受key
进行搜索,我们需要将此array
和key
传递给搜索函数,该函数将返回{ {1}}或true
取决于数组中是否存在false
。
key
答案 4 :(得分:0)
要在数组中查找值,您应该遍历它并将每个值与所需数字进行比较。您还应该检查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;
}