c - 以 float 形式打印数组,其中大小取决于用户输入

标签 c arrays floating-point printf

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

我的问题是我的阵列打印的数字多于所需的五个数字。这五个数字是 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;
}

这是程序的输出:

[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

最佳答案

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

#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;
}

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

#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;
}

请注意,上述两种方法都将 q(或用户键入的任何非整数)留在 stdin 中。您可以使用

stdin 清除它
int c;
while((c = getchar()) != '\n' && c != EOF);

在第一个 for 循环之后。

关于c - 以 float 形式打印数组,其中大小取决于用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33062631/

相关文章:

c - Nasm,没有打印正确的值

c - 如何计算传递给函数的数组的大小

c++ - 可以使用 gcc 中的多个对齐属性来保证缓存行分离吗?

c - C 中的数组及其指针

javascript - 在 Angular 上从数组中搜索过滤器

c - 浮点运算结果如何舍入?

c - 在 VSCode 中使用 gcc 编译 C 程序时出错

arrays - JSON数据/方括号剥离

java - 如何扫描数组以获取某些信息

c - 使用大数时,函数 pow() 无法正常工作?