scanf需要的输入多于请求的数量

时间:2014-01-28 11:20:17

标签: c scanf

我正在尝试使用scanf从用户那里获得5个浮点值,问题是用户需要输入6个值才能完成程序。 虽然我知道我不应该使用scanf,但令我困扰的是,我无法理解它。有关如何使用scanf修复它的任何见解,建议吗?

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

int main()
{
int i = 0 , j = 0;
char buf[128] = {0};

float numbers[5] = {0.0};
float keep = 0.0;

printf("Please input 5 numbers : \n");

for (i = 0; i < 5; i++)
{
 scanf("%f\n", &numbers[i]);
}

printf("Done!");

谢谢,

MIIJ

2 个答案:

答案 0 :(得分:1)

scanf("%f\n", &numbers[i]);应为scanf("%f", &numbers[i]);

答案 1 :(得分:1)

你必须删除scanf()函数中的\ n

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

int main()
{
    int i = 0 , j = 0;
    char buf[128] = {0};

    float numbers[5] = {0.0};
    float keep = 0.0;

    printf("Please input 5 numbers : \n");

    for (i = 0; i < 5; i++)
    {
        scanf("%f", &numbers[i]);
        printf("number %i is %f \n",i,numbers[i]);
    }

    printf("Done!");

    return 0;
}