【发布时间】:2015-10-11 07:35:01
【问题描述】:
我有一个家庭作业,要求用户输入一组实数。我必须将这些存储到一个大小为 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;
}
这是程序的输出:
[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
【问题讨论】:
-
我在这里看到的第一个问题:您提示用户输入实数,但期望输入整数。
-
您应该始终在编译时出现警告并在最新版本的 C 中编译,即使用
gcc jperez_aver.c -Wall -Wextra -pedantic -std=c11。 -
第二个问题:无论实际输入了多少值,都要打印整个数组。
标签: c arrays floating-point printf