程序编译完美,问题是循环,没有显示位置
这里是库 stdio.h 的包含
int main(void)
{ int x, i=0,j=0, a[100];
char sal;
printf("Este programa lee un arreglo de numeros enteros y un numero x, y muestra en pantalla los indices de las posiciones en donde se encuentra ese numero x\n");
do
{
printf("Ingrese un numero: ");
scanf("%i", &a[i]);
i++;
printf("Si desea salir presione s: ");
scanf(" %c", &sal);
}while(sal!='s');
printf("Ingrese el valor de la variable x: ");
scanf("%i", &x);
for (j; j<=i; j++)
{
if(a[i]==x)
printf("%i",i);
}
printf("\n");
}
最佳答案
您的 for
状况循环应该是 j<i
, 不是 j<i+1
.当 while
循环退出,i
具有下一个输入的值,但尚未设置,因为
循环退出。
您还使用索引 i
而不是 j
在for
-环形。 j
是个
运行索引,不是 i
:
for (j; j<i; j++)
{
if(a[j]==x)
printf("%i", j);
}
是正确的。
你的 while
循环还可以,但有点笨拙。首先你不检查你是否
写入超过 a
的限制.条件应该是
while(sal!='s' && i < (sizeof a / sizeof *a));
这样用户不能输入超过a
的值可以坚持。
退出循环的方式也很尴尬,用户必须输入一些东西
不同于 s
继续并且它只能是一个字符。这将是
更好:
int c;
char line[100] = { 0 };
do
{
printf("Ingrese un numero: ");
scanf("%i", &a[i]);
while((c = getchar()) != '\n' && c != EOF); // to clear the input buffer
i++;
printf("Si desea salir ingrese SALIR. Para continuar presione ENTER: ");
fgets(line, sizeof line, stdin);
} while(strcmp(line, "SALIR\n") && strcmp(line, "salir\n") && i < (sizeof a / sizeof *a));
请注意 strcmp
当字符串相等时返回 0,否则返回非零值。
关于c - C语言for循环中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48858100/