在float中打印数组,其中size依赖于用户输入

Mar*_*TEP 0 c arrays floating-point printf

我有一个家庭作业,要求用户输入一组实数.我必须将它们存储到大小为20的数组中,并且必须在floats中打印数组.

我的问题是我的阵列打印的数量超过了所需的五个数字.五个数字是10, 37, 15, 21, 18.

我需要帮助只打印五个数字,float一个小数位.

我在Oracle VM VirtualBox中使用Centos6.7,使用gedit文本编辑器.任何帮助表示赞赏.

#include <stdio.h>
#define SIZE 20


int main(void)
{
    int i, inputs[SIZE];

    printf("Enter real numbers, up to %d, q to quit\n", SIZE);
    for(i=0; i < SIZE; i++)
        scanf("%d", &inputs[i]);

    printf("You entered the following values:\n");
    for(i=0; i < SIZE; i++)
        printf("%4d", inputs[i]);
    printf("\n");

return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是该程序的输出:

[ee2372@localhost cprog]$ gcc jperez_aver.c
[ee2372@localhost cprog]$ ./a.out 
Enter real numbers, up to 20, q to quit
10 37 15 21 18 q
You entered the following values:
  10  37  15  21  18   04195443   0-503606696327674196037   0-891225184  494195968   0   0   04195552   0
Run Code Online (Sandbox Code Playgroud)

Spi*_*rix 5

您必须跟踪用户输入的数量.为此,您需要一个新变量.如果用户输入整数,则递增它.这样的东西就足够了:

#include <stdio.h>

#define SIZE 20

int main(void)
{
    int i, count = 0, inputs[SIZE];      /* Note the new variable */

    printf("Enter real numbers, up to %d, q to quit\n", SIZE);
    for(i = 0; i < SIZE; i++)
    {
        if(scanf("%d", &inputs[i]) == 1) /* If `scanf` was successful in scanning an `int` */
            count++;                     /* Increment `count` */
        else                             /* If `scanf` failed */
            break;                       /* Get out of the loop */
    }

    printf("You entered the following values:\n");
    for(i = 0; i < count; i++)           /* Note the change here */
        printf("%4d", inputs[i]);

    printf("\n");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您希望用户输入具有小数的数字,您应该使用:

#include <stdio.h>

#define SIZE 20

int main(void)
{
    int i, count = 0;
    float inputs[SIZE];                  /* For storing numbers having decimal part */

    printf("Enter real numbers, up to %d, q to quit\n", SIZE);
    for(i = 0; i < SIZE; i++)
    {
        if(scanf("%f", &inputs[i]) == 1) /* If `scanf` was successful in scanning an `float` */
            count++;                      /* Increment `count` */
        else                              /* If `scanf` failed */
            break;                        /* Get out of the loop */
    }

    printf("You entered the following values:\n");
    for(i = 0; i < count; i++)
        printf("%.1f \n", inputs[i]); /* Print the number with one digit after the decimal, followed by a newline */

    printf("\n");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

请注意,上述两种方法都留下q(或用户键入的任何非整数)stdin.您可以stdin通过使用来清除它

int c;
while((c = getchar()) != '\n' && c != EOF);
Run Code Online (Sandbox Code Playgroud)

在第一个for循环之后.