C程序数组和for循环练习

标签 c arrays

我必须编写一个函数来使用 for 循环检查一个值是否位于具有 N 个元素的数组中。我编写了代码

 #include <stdio.h>
int main ()
int N[100],n,i; 
printf ("Write the value of n:");
scanf ("%d",&n);
i=0;

      printf ("Write the value of the element :");
      scanf ("%d",&v[i]);
      for (i=0,i<n,i++)
      {
          if (N[i]==n)
          }
          printf ("The value is located in the array :");



return 0;               

当我编译它时,它在 printf 之前说语法错误。这是什么意思?我做错了什么?

最佳答案

基本语法问题。尝试:

#include <stdio.h>

int main(void)
{
    int N[100],n,i; 
    printf ("Write the value of n:");
    scanf ("%d",&n);
    i=0;
    printf("Write the value of the element :");
    scanf("%d", &v[i]);  /* v doesn't exist */

    /* you are looping up to n, which could be anything */
    for (i=0; i<n; i++)
    {
        /* you never populate N, so why would you expect n to be found?
        the value of any element in N is indeterminate at this point */
        if (N[i]==n)
        {
            printf ("The value is located in the array :");
        }
    }      

    return 0;
}

也就是说,你这里有逻辑问题:

  1. v 未在任何地方声明。
  2. 您永远不会填充数组 (N)。
  3. n是用户输入的值,不是数组的上限。如果我输入 101 会怎么样?

这些不仅仅是语法问题,您还需要修复您的逻辑。

关于C程序数组和for循环练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23120448/

相关文章:

c - 分配二维数组的一维并返回

javascript - 了解数组的子集

如果在 List 或 Map 中对数组进行注释,则 Java 8 TYPE_USE 注释不起作用

c - 如何验证 ARGV 中的 key ?

c - 在进程之间传递值

c - 结构体中的数组分配

c - 如何计算这个阶乘

c# - 请求数组到另一个类

c++ - 静态数组缓冲区分配

将指针数组值复制到 C 中另一个数组的末尾