我必须编写一个函数来使用 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;
}
也就是说,你这里有逻辑问题:
v
未在任何地方声明。- 您永远不会填充数组 (
N
)。 n
是用户输入的值,不是数组的上限。如果我输入 101 会怎么样?
这些不仅仅是语法问题,您还需要修复您的逻辑。
关于C程序数组和for循环练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23120448/