简体   繁体   中英

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. However, when running it, the user is forced to input 11 numbers, but the 11th one is discarded anyway. 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.

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.

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.

Even after 10th element is entered, scanf waits for a non-whitespace character to be entered before it is done. After the 10 numbers have been entered, you can enter any old non-whitespace character to let scanf finish.

Remove the \\n from the format string. You don't need it. Use

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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