2013-04-28 76 views
2

我正在創建一個函數來讀取來自用戶的輸入並將它們放入一個浮點數組中,該數組的預定大小爲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

回答

6

正確的格式說明問題很多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