简体   繁体   English

C:for循环中的Scanf函数运行时间比预期时间长

[英]C: Scanf function in for loops runs one more time than it should

In the following code, I want the user to input 10 floating point numbers, and then take the average of them. 在下面的代码中,我希望用户输入10个浮点数,然后取它们的平均值。 However, when running it, the user is forced to input 11 numbers, but the 11th one is discarded anyway. 但是,运行它时,用户被迫输入11个数字,但是第11个数字还是被丢弃了。 The value of the average actually turns out to be correct. 平均值实际上是正确的。 I just want to know why the scanf seems to run 1 extra time. 我只想知道为什么scanf似乎要多运行1次。

The problem I faced was different than that of the suggested duplicate. 我遇到的问题与建议的重复问题不同。 Here, the problem was related to my understanding of the scanf function, I actually looped the correct amount of times. 在这里,问题与我对scanf函数的理解有关,实际上我循环了正确的时间。

see: 看到:

#include <stdio.h>

int main (void)
{
    int     i;
    float   entry[10];
    float   total = 0.0;

    printf("please enter 10 floating point numbers\n");

    for (i = 0; i < 10; ++i)
        scanf("%f\n", &entry[i]);

    for (i = 0; i < 10; ++i) {
        total = total + entry[i];
    }

    printf("The average of the 10 floating point numbers is: %f\n", total / 10);

    return 0;
}

The \\n in the format string is causing that. 格式字符串中的\\n导致了这种情况。

Even after 10th element is entered, scanf waits for a non-whitespace character to be entered before it is done. 即使输入了第10个元素, scanf也会在完成输入之前等待输入非空白字符。 After the 10 numbers have been entered, you can enter any old non-whitespace character to let scanf finish. 输入10个数字后,您可以输入任何旧的非空白字符以使scanf完成。

Remove the \\n from the format string. 从格式字符串中删除\\n You don't need it. 不用了 Use 采用

for (i = 0; i < 10; ++i)
    scanf("%f", &entry[i]);

删除scanf内的\\n ,即在第一个for循环内,写:

scanf("%f",&entry[i]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM