我想知道用户输入的数字是否是数组中的数字。
这是我的代码:
#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");
}
}
但是这不起作用。
如何将数组中的一个数字与另一个数字进行比较?
注意:我不知道指针,所以我需要在没有指针的情况下完成它。
最佳答案
为什么它不起作用以及代码有什么问题?
- 您只比较一个值,而不是所有数组元素。
scanf
循环后i
的值为 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 :)
}
}
}
关于c - 如何将数组中的数字与另一个数字进行比较? [C],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34694824/