为什么我在这个简单的程序中得到随机垃圾值?

时间:2014-07-25 07:27:08

标签: c

我想从终端读取一些号码,然后打印出来。 但是,它们似乎都是某种随机值而不是我提供的值。

为什么我的输入没有正确保存?

int main (void)
{    
    int i = 0 , numeros[21] , cont = 1, z = 0;

    puts("\n === Bienvenido ===\n"); 
    puts("\n === Vamos a procesadar  un numero de serie de 20 digitos [Numericos] ===\n");  
    puts("\n === Dime los numeros ===\n"); 

    while (cont != 20 )
    {
        fflush(stdin);
        scanf("%d", &numeros[i]);      

        printf("\n === Dime otro numero. Numeros: %d ===\n", cont); 
        cont++;
    }
    for (z = 0; z < 20; z++)
    {
        printf("\nLos numeros son: %d\n", numeros[z]);
    }
    system("pause");
}

5 个答案:

答案 0 :(得分:2)

好的,有几个问题:

  • numeros被声明为21个整数的数组,但您使用它就好像是numeros[20]
  • 未定义的行为,因为您在fflush
  • 上呼叫stdin
  • scanf("%d", &numeros[i]),虽然不安全,但一切都很好,但i永远不会增加
  • 检查函数的返回值...始终:scanf返回其扫描的值的数量,如果它返回0,则不扫描%d,并且numeros[i]需要重新分配。

以下是我编写程序的示例:

#include <stdio.h>
#include <stdlib.h>

int main ( void )
{
    int c,i=0,
        numbers[20],
        count=0;
    //puts adds new line
    puts("enter 20 numbers");
    while(count < 20)
    {
        c = scanf(" %d", &numbers[i]);//note the format: "<space>%d"
        if (c)
        {//c is 1 if a number was read
            ++i;//increment i,
            ++count;//and increment count
        }
        //clear stdin, any trailing chars should be ignored
        while ((c = getc(stdin)) != '\n' && c != EOF)
            ;
    }
    for (i=0;i<count;++i)
        printf("Number %d: %d\n", i+1, numbers[i]);
    return 0;
}

答案 1 :(得分:1)

您没有在第一个循环中递增i

答案 2 :(得分:1)

您正在递增cont,但使用numeros[i]来存储您的输入。由于i永远不会更改,因此您只能写入第一个数组元素。将i更改为cont,如

scanf("%d", &numeros[cont]);

答案 3 :(得分:0)

您想要达到什么目标?我看到你正在从i=0输入你的numeros数组的stdin索引。然后你通过这个数组迭代,但你刚刚输入了一个数字!您应该可以将numeros数组的子包更改为cont:

scanf("%d", &numeros[cont]); 

答案 4 :(得分:0)

scanf("%d", &numeros[i]); 

应替换为

scanf("%d", &numeros[cont]);

当你正在递增续而不是我

相关问题