简体   繁体   中英

Reading an array with floating point numbers (C programming language)

I am creating a function to read in inputs from the user and put them into a floating point array of numbers with predetermined fix size of 25. It also returns the total amount of items that the user enters. However, for some reason this code will not terminate when I enter 999. I know it is something to do with that it is an int and input is a float, but I don't really know how to fix this (only been learning C for five days).

int readArray(float a[]){
    //accepts inputs and puts items in a predefined array of size 25    
    int index = 0;
    float input;
    printf("Enter 25 or less elements for array (999 to finish):\n");

    scanf("%d", &input);  //accept initial response; priming prompt
    printf("1st Prompt accepted");

    while (input != 999 && index < 25) {
        printf("In while loop");

        a[index] = input;
        index++;
        scanf("%d", &input);
    }
    return (index);

}

正确的格式说明符在这里很重要。对于float来说是%f 。因此将您的scanf()更改为

scanf("%f", &input);

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