用浮点数读取数组(C编程语言)

问题描述:

我正在创建一个函数来读取来自用户的输入并将它们放入一个浮点数组中,该数组的预定大小为25,它还返回总数用户输入的项目。但是,由于某些原因,当我输入999时,这段代码不会终止。我知道这是一个int,输入是一个float,但我不知道如何解决这个问题(只有学习C五天)。用浮点数读取数组(C编程语言)

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); 

} 
+0

哦刚刚意识到,这两个打印:输出(“第一次提示接受”);和printf(“在while循环中”);只是调试代码。 – Jared 2013-04-28 02:58:54

+0

[读取浮动数组]的可能重复(http://stackoverflow.com/questions/843577/reading-floats-into-an-array) – joce 2013-04-28 03:41:33

正确的格式说明问题很多here.For浮动是%f。所以改变你的scanf()

scanf("%f", &input); 
+5

对于downvoter,我敢于接受C中的'float'数字使用'scanf()'的'%d'格式说明符。告诉我如何在'floats'中使用'%d',我会放弃C并去阿富汗并在那里种植罂粟。 – 2013-04-28 03:10:43

+0

非常感谢!这使得阅读工作。谢谢! – Jared 2013-04-28 03:15:55

+0

为什么downvote? – 2013-04-28 03:21:00