c - 如何将数组中的数字与另一个数字进行比较? [C]

标签 c arrays if-statement

我想知道用户输入的数字是否是数组中的数字。

这是我的代码:

#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/

相关文章:

c 如何检查数组的第一个字符

java - 需要帮助了解程序的执行

java - 返回对数组的引用是什么意思?

PHP循环几个月,从12月开始

php - MySQL:如果列值为 2,则执行 X ELSE 执行 Y

java - Android 应用程序上的 if 语句帮助

C编程: why are my decimals not displaying & how do I define black spaces

c++ - 如何检查 CD 驱动器在 Linux 中是打开还是关闭?

c - 确定 SDL_CreateTexture() 的正确像素格式?

java - 将 Character[] 的范围转换为 String