2011-02-15 48 views
-1

我的挑戰是編寫一個程序,將用戶的GPA作爲浮點值存儲在數組中。用戶最多可以輸入30個GPA,並在每個輸入值輸入後顯示平均值。我感到困惑的是如何在循環中使用scanf()函數來將浮點值存儲在數組中。任何人都可以用示例代碼解釋嗎?如何分配用戶輸入以存儲到數組

好吧,這是我已經開始的代碼。我知道這是假的,但我希望每個人都能更好地瞭解我正在編寫的程序。我希望用戶輸入他們有多少GPA。他們輸入的數字將是我將擁有的數組數量。

#include <stdio.h> 
main() 
{ 
    int loopcount = 0; 
    int NumGpa = 0; 
    NumGpa = 0 - 1; 
    float = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25; 
    int gpa[NumGpa] ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}; 
    int i = 0; 
    int total =0; 

    printf("\t\tWelcome to the GPA calculator.\n "); 
    printf("Please enter the number of classes you have counted for you GPA: "); 
    scanf("%d", &NumGpa); 

    while (loopcount &lt; NumGpa) 
    { 
     printf("\nenter your first GPA: "); 
     scanf("%d", &1); //??????????????(i want loops to use scanf() if order &2,&3 ect? 

     for (i=0; i&lt;gpa; i++) 
     { 
      total += arbin[NumGpa]; 
     } 

     printf(" you average gpa is %d", NumGpa/????); 
     getchar(); 
    } 
} 
+0

OK所以這是代碼,我已經開始我知道它BOGUS但希望每個人都獲得程序IM試圖寫一個更好的想法。我希望用戶輸入多少GPA的信息。他們輸入的數字將是我將擁有的陣列數量。 – Arbin 2011-02-15 05:35:52

+4

如果您關閉大寫鎖定鍵,則可以減少虛假。保證讓你成爲更好的程序員。 – 2011-02-15 06:40:09

回答

0

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

+0

小錯字 - 你想'&arrayVariableName`。 – 2011-02-15 04:32:23

0

當您閱讀與scanf一個float,您傳遞有關float的地址。您可以使用address-of運算符(&),以與其他任何方式相同的方式獲取數組中項目的地址。

或者,您可以簡化一些事情。在C中,下標運算符([])等同於指針操作。特別是,a[b]相當於*(a+b)。然而,&*幾乎是完全相反的,所以在這種情況下,他們最終會取消彼此。因此,如果您願意,您可以使用a+b,其中一個是數組的名稱,另一個是您想要讀取的數組中項目的索引。

0
int i = 0; // current user 
float user_gpa[NUM_USERS]; // your array 

while (i < num_users) { 
    scanf("%f", &user_gpa[i]); // reading data for the i-th user (%f means float) 
    i = i + 1; // next user 
} 
0

試試這個

for(i=0; i<30; i++) 
scanf("%f", arrayname[i]); 

如果你想直接平均再試試這個

float temp, ave=0; 
int i; 
for (i=1; i<=30; i++) 
{ 
scanf("%f", &temp); 
ave += temp; 
} 
printf("%f", ave/30); 
0

喏,你的代碼少了不少錯誤,或許這可能幫助。

enter code here 

void main()(
    int loopcount = 0; 
    int NumGpa; 
    NumGpa = 0 - 1; 
/* 
    float = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25; i don't understand why were you doing this. 
    int gpa[NumGpa] ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}; 
*/ 
    int i = 0; 
    float total =0; /this is float so that output will be accurate. 
    printf("\t\tWelcome to the GPA calculator.\n"); 
    printf("Please enter the number of classes you have counted for you GPA: "); 
    scanf("%d", &NumGpa); 
    int gpa[NumGpa]; 
    while (loopcount < NumGpa) 
    { 
     printf("\nenter your %d GPA: ", loopcount); 
     scanf("%d", &gpa[loopcount]); 
     loopcount++; 
    } 
    for (i=0; i<NumGpa; i++) 
    { 
     total += gpa[i]; 
    }  
     printf(" you average gpa is %f", total/NumGpa); 
     getchar(); 
}